编程语言
首页 > 编程语言> > javascript-从对象中动态删除多个键/值对

javascript-从对象中动态删除多个键/值对

作者:互联网

假设我有一系列对象.我不想使用某些键/值.删除一个键/值对的传统方法是按以下方式使用delete:

for (var i = 0; i < tracks.length; i++) {
  delete tracks[i]["currency"];
  ...
}

我要放入的对象可能有30多对.有没有一种方法可以说明我想要哪些对并删除所有其他对?例如,在这个对象数组中,我只想保留trackName,kind,price

var tracks = [{
    trackNumber: "01",
    trackName: "Track 1",
    trackDuration: "5:35",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "02",
    trackName: "Track 2",
    trackDuration: "5:15",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "03",
    trackName: "Track 3",
    trackDuration: "5:07",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "04",
    trackName: "Track 4",
    trackDuration: "0:16",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "05",
    trackName: "Track 5",
    trackDuration: "5:35",
    kind: "song",
    currency: "USD",
    price: 1.29
}];

解决方法:

对数组进行迭代,并保留每个对象想要的内容.

var keep = ['trackName', 'kind', 'price'];

for(var i = 0;i < tracks.length; i++){

    for(var key in tracks[i]){
        if(keep.indexOf(key) === -1)delete tracks[i][key];
    }

}

标签:key-value,arrays,json,javascript,object
来源: https://codeday.me/bug/20191028/1952640.html