所以,我有:
"people": [
{
"first": "Linda",
"last": "Donson",
"salary": "4000USD"
},
{
"first": "Mark",
"last": "Sullivan",
"salary": "3500USD"
},
];
现在,我想将其转换为一个仅包含所需数据集的对象新数组。 例如:
"people": [
{
"first": "Linda",
"salary": "4000USD"
},
{
"first": "Mark",
"salary": "3500USD"
},
];
我该怎么做?因此,它应该取出"last"
键及其值,并且仅返回"first"
和"last"
。
谢谢
答案 0 :(得分:2)
您可以使用map函数获取具有所需选项的新数组 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var source = [ { first: 'first1', last: 'last1', property1: 'p1-1' }, { first: 'first2', last: 'last2', property1: 'p1-2' }];
var mapped = source.map( function (e) {
return { first: e.first, property1: e.property1 }
})
console.log('mapped : ', mapped)
答案 1 :(得分:2)
这实际上是通过map
和delete
或map
和ES6 destructuring
的一个简单的班轮,如以下两个示例所示:
var data = [{
"first": "Linda",
"last": "Donson",
"salary": "4000USD"
},
{
"first": "Mark",
"last": "Sullivan",
"salary": "3500USD"
}
]
console.log(data.map(x => delete(x.salary) && x))
此外,如果您担心要更改对象,则可以使用ES6 destructuring
和short object literal notation
来实现:
Object.values(data).map(({first, last}) => ({first, last}))
答案 2 :(得分:1)
您可以使用forEach
var peoples = [{
"first": "Linda",
"last": "Donson",
"salary": "4000USD"
},
{
"first": "Mark",
"last": "Sullivan",
"salary": "3500USD"
},
];
// empty array
var newPeoples = [];
peoples.forEach((people) => {
// only push desired object inside empty array
newPeoples.push({
"first": people.first,
"salary": people.salary
});
});
// desired array of objects
console.log(newPeoples);