1

I have this json:

json = [{
    "code3": "ALB",
    "asset": 9,
    "biodiversity": 4,
    "infrastructure": 15
}, {
    "code3": "GHN",
    "asset": 4,
    "biodiversity": 5,
    "infrastructure": 5,
}, {
    "code3": "TGO",
    "asset": 3,
    "biodiversity": 6,
    "infrastructure": 7
}]

I am trying to filtering it down to this in a for loop:

result = [{
    "code3": "ALB",
    "asset": 9
}, {
    "code3": "GHN",
    "asset": 4
}, {
    "code3": "TGO",
    "asset": 3
}]

What is the fastest way to do this. I know I could use json.forEach(j => del j["infrastructure"] ... or something similar but I am looking to filter out by the keys code3, asset instead

3

2 Answers 2

2

let json = [
     {
          "code3": "ALB",
          "asset": 9,
          "biodiversity": 4,
          "infrastructure": 15
     },
     {
          "code3": "GHN",
          "asset": 4,
          "biodiversity": 5,
          "infrastructure": 5,
      },
      {
           "code3": "TGO",
           "asset": 3,
           "biodiversity": 6,
           "infrastructure": 7
      }
];

let result = json.map(({code3, asset}) => ({code3, asset}));

console.log(result);

This might be confusing at first, so let's see how it works:

  • The .map method creates a new array with the output from the function on each element in the previous array.
    • Example:
let nums = [0, 1, 2, 3];
let add1 = n => n + 1;

// The following two statements are equivalent:
nums = [add1(num[0]), add1(num[1]), add1(num[2]), add1(num[3])];
nums = nums.map(add1);
  • Object destructuring is the way that we get the input from the arrow function. It's a bit hard to explain, so perhaps this article will guide you through it:
  • Lastly, we have object shorthand properties. This is how we return the result from the arrow function. If you have a variable with the same name as the property of an object and the same value as the value of that property, you can add it to the object without specifying the value.
    • Example:
let a = 'foo', b = 42, c = {};
let o = {a, b, c}

// o = { a: 'foo', b: 42, c: {} }

Hopefully putting these parts together is intuitive by itself.

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

Comments

1

You can use .map:

let json = [
     {
          "code3": "ALB",
          "asset": 9,
          "biodiversity": 4,
          "infrastructure": 15
     },
     {
          "code3": "GHN",
          "asset": 4,
          "biodiversity": 5,
          "infrastructure": 5,
      },
      {
           "code3": "TGO",
           "asset": 3,
           "biodiversity": 6,
           "infrastructure": 7
      }
];

let list = json.map(e => {
     return {
          code3: e.code3,
          asset: e.asset
     }
});

console.log(list);

1 Comment

Even shorter as .map(({code3, asset}) => ({code3, asset}))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.