1

I am receiving following data in the form of json

 [{
     "Id": 1,
     "sku": "abc",
     "name": "Abbey Black Round Glass and Chrome 3 Tier Stand",
     "qty": 14
   },
   {
     "Id": 3,
     "sku": "abc",
     "name": "Ammy Black Glass and Chrome 5 Tier Corner Stand",
     "qty": 0
   },
   {
     "Id": 4,
     "sku": "abc",
     "name": "Barcelona Adjustable Gas Lift Black Bar Stool (Set of 2)",
     "qty": 0
   }
 ] 

I have to filter data so that it shows only following key-value pair

sku
qty

Expected result will be

[{
    "sku": "abc",
    "qty": 14
  },
  {

    "sku": "abc",
    "qty": 0
  },
  {

    "sku": "abc",
    "qty": 23
  }
]

Any solution to filter data in such a format?. I can filter data based on specific values but I want json data containing only two pairs (sku,qty)

2 Answers 2

1

You can use Array.map() with array destructuring to make your code simple and short:

var data = [
  {
      "Id": 1,
      "sku": "abc",
      "name": "Abbey Black Round Glass and Chrome 3 Tier Stand",
      "qty": 14
  },
  {
      "Id": 3,
      "sku": "abc",
      "name": "Ammy Black Glass and Chrome 5 Tier Corner Stand",
      "qty": 0
  },
  {
      "Id": 4,
      "sku": "abc",
      "name": "Barcelona Adjustable Gas Lift Black Bar Stool (Set of 2)",
      "qty": 23
   }
];
var res = data.map(({sku, qty}) => ({sku, qty}));
console.log(res);

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

1 Comment

@mohammadobaid glad to help
1

You can do it with map like this:

var array=[
    {
        "Id": 1,
        "sku": "abc",
        "name": "Abbey Black Round Glass and Chrome 3 Tier Stand",
        "qty": 14
    },
    {
        "Id": 3,
        "sku": "abc",
        "name": "Ammy Black Glass and Chrome 5 Tier Corner Stand",
        "qty": 0
    }];

array.map(function(item) { 
    delete item.Id; 
delete item.name; 
    return item; 
});

1 Comment

Thanks for the help , however above answer works seamlessly for me

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.