简体   繁体   中英

How to return not all of the properties of an object from arrays with an array method?

I want to use an array method with arrow function. For an example:

 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 ); 

What if i want to return just the object with the name and type properties? Like this: console.log(result) //[{name: 'mangos', type: 'a'}, {name: 'cherries', type: 'a'}]

You'd create a new object. It looks like you want to do two things, though: Filter to only items with quantity of 5, and return objects without the quantity field. Unelss you have hundreds of thousands of these¹, you'd do that by using filter then map . Here's an example with destructuring:

 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); 


¹ If you do have hundreds of thousands of these or more, you might consider just making one pass with forEach .

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

map使用您提供的值创建一个新数组,但不会更改原始数组,filter仅使用该函数返回真实值的值创建一个数组。

You can remove the type property by destructuring:

 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); 

Or you can just make your array.map callback returning object having only name and quantity field:

 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); 

Try using 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}
} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM