我有一个对象,我想返回两个值并将它们映射为1个对象。
宾语
Itemlist:[
{name: 'Chicken', searchParam: 'chicken', search: true},
{name: 'table', searchParam: 'table', search: false},
{name: 'books', searchParam: 'books', search: true}]
想要从Itemlist searchParam返回并搜索并映射到结果为的对象:
{chicken: true},{table: false},{books: true},
所以回报会像
{ Itemlist[0].searchParam :Itemlist[0].search }
最佳答案
您可以使用array#map
从对象列表的每个对象中获取包含name
和search
值的对象数组。
var itemlist = [{name: 'Chicken', searchParam: 'chicken', search: true},{name: 'table', searchParam: 'table', search: false},{name: 'books', searchParam: 'books', search: true}];
var result = itemlist.map(({searchParam, search}) => ({[searchParam]: search}));
console.log(result);
ES5代码:
var itemlist = [{name: 'Chicken', searchParam: 'chicken', search: true},{name: 'table', searchParam: 'table', search: false},{name: 'books', searchParam: 'books', search: true}];
var result = itemlist.map(function(item) {
var obj = {};
obj[item.searchParam] = item.search;
return obj;
});
console.log(result);