0

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

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

ES2015:

const arrayExampleNew = arrayExample.map(({productId, quantity}) => ({productId, quantity}));
answered Sep 22, 2016 at 11:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.