Reputation: 303
I Have this array:
var arrayExample = [
{productId: 1, quantity: 2, name: example, description: example},
{productId: 1, quantity: 2, name: example, description: example},
{productId: 1, quantity: 2, name: example, description: example},
{productId: 1, quantity: 2, name: example, description: example}];
My question is
How do I get all the items of the array but taking in every object only the productId and quantity? Thus having an array that contains all the objects but only with the two values? The number of the objects of the array is variable
Result:
var arrayExampleNew = [
{productId: 1, quantity: 2},
{productId: 1, quantity: 2},
{productId: 1, quantity: 2},
{productId: 1, quantity: 2}];
sorry for my English
Upvotes: 0
Views: 42
Reputation: 318302
You could just map it
var arrayExample = [{
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}, {
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}, {
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}, {
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}];
var arr = arrayExample.map(function(item) {
return {productId : item.productId, quantity : item.quantity }
});
console.log(arr)
Upvotes: 5
Reputation: 1748
ES2015:
const arrayExampleNew = arrayExample.map(({productId, quantity}) => ({productId, quantity}));
Upvotes: 1