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
asked Sep 22, 2016 at 11:12
Edoardo Goffredo
3132 gold badges5 silver badges20 bronze badges
2 Answers 2
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)
answered Sep 22, 2016 at 11:15
adeneo
319k29 gold badges410 silver badges392 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
ES2015:
const arrayExampleNew = arrayExample.map(({productId, quantity}) => ({productId, quantity}));
Comments
lang-js