如何使用数组方法从数组返回不是对象的所有属性?

时间:2018-05-14 11:53:56

标签: javascript

我想使用带箭头功能的数组方法。举个例子:



const inventory = [
    {name: 'apples', quantity: 2, type: 'a'},
    {name: 'bananas', quantity: 0, type: 'a'},
    {name: 'cherries', quantity: 5, type: 'a'}
    {name: 'mangos', quantity: 5, type: 'a'}
];

const result = inventory.filter( fruit => fruit.quantity === 5 );




如果我想仅返回具有名称和类型属性的对象,该怎么办?像这样:     console.log(result) //[{name: 'mangos', type: 'a'}, {name: 'cherries', type: 'a'}]

4 个答案:

答案 0 :(得分:4)

你要创建一个新对象。看起来你想做两个的事情:过滤到只有数量为5的项目,返回没有数量字段的对象。 Unelss你有成千上万的¹,你可以使用filter然后map来做到这一点。这是一个解构的例子:

const inventory = [
    {name: 'apples', quantity: 2, type: 'a'},
    {name: 'bananas', quantity: 0, type: 'a'},
    {name: 'cherries', quantity: 5, type: 'a'},
    {name: 'mangos', quantity: 5, type: 'a'}
];

const result = inventory
  .filter(fruit => fruit.quantity === 5)
  .map(({name, type}) => ({name, type}));

console.log(result);

¹如果您有数十万或更多这些或更多,您可以考虑只使用forEach进行一次传递。

答案 1 :(得分:1)

inventory.filter(fruit => fruit.quantity === 5).map(fruit => ({ name: fruit.name, type: fruit.type }));

map使用您提供的值创建一个新数组,但不会更改原始数据,过滤器仅使用函数返回的值为truthy值创建数组。

答案 2 :(得分:0)

您可以通过解构删除type属性:

const inventory = [
    {name: 'apples', quantity: 2, type: 'a'},
    {name: 'bananas', quantity: 0, type: 'a'},
    {name: 'cherries', quantity: 5, type: 'a'},
    {name: 'mangos', quantity: 5, type: 'a'}
];

const res = inventory.map(({type: x, ...rest}) => rest);

console.log(res);

或者你可以让你的array.map回调返回只有名字和数量字段的对象:

const inventory = [
    {name: 'apples', quantity: 2, type: 'a'},
    {name: 'bananas', quantity: 0, type: 'a'},
    {name: 'cherries', quantity: 5, type: 'a'},
    {name: 'mangos', quantity: 5, type: 'a'}
];

const res = inventory.map(({name, quantity}) => ({name, quantity}));

console.log(res);

答案 3 :(得分:-4)

尝试使用lodash

const inventory = [
    {name: 'apples', quantity: 2, type: 'a'},
    {name: 'bananas', quantity: 0, type: 'a'},
    {name: 'cherries', quantity: 5, type: 'a'}
    {name: 'mangos', quantity: 5, type: 'a'}
];

const result = ._map( inventory, (item)=> { 
    return {
             name: item.name, 
             quantity: item.quantity}
} );