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

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)

Sign up to request clarification or add additional context in comments.

Comments

1

ES2015:

const arrayExampleNew = arrayExample.map(({productId, quantity}) => ({productId, quantity}));

Comments

Your Answer

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.