Khang Nguyen
Khang Nguyen

Reputation: 67

get values in an array inside an array

I have a question here I want to get all the value of the values array inside this array.

const sample = [
  {
    "key": "sampleKey", "values":
      [
        { "key": "insidesampleKey", "value": 2 },
        { "key": "insideofinside", "value": 2 }
      ]
  },

  { 
    "key": "sampleKey2", "values": 
      [
        { "key": "insideSampleKey2", "value": 1 }
      ] 
  },

  { 
    "key": "samplkey3", "values": 
      [
        { "key": "insideofsampleKey3", "value": 1 }
      ] 
  }
]

So far, I can only print the first one console.log(sample[0].values[0].value). I appreciate with any helps. Thanks much and have a great weekend

Upvotes: 1

Views: 221

Answers (4)

user10931450
user10931450

Reputation:

I think flatMap may be the best way to deal with this.

sample.flatMap(outer => outer.values.map(inner => inner.value))

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44107

If you want to print the other value properties, just map over the array, then look at the values array, then look at value, and finally use flat to get a single array:

const sample = [{
    "key": "sampleKey",
    "values": [{
      "key": "insidesampleKey",
      "value": 2
    }, {
      "key": "insideofinside",
      "value": 2
    }]
  },

  {
    "key": "sampleKey2",
    "values": [{
      "key": "insideSampleKey2",
      "value": 1
    }]
  },

  {
    "key": "samplkey3",
    "values": [{
      "key": "insideofsampleKey3",
      "value": 1
    }]
  }
];

console.log(sample.map(e => e.values.map(x => x.value)).flat(1));

Upvotes: 0

JohanP
JohanP

Reputation: 5472

You can use reduce and concat to get a flat, single array.

const sample = [{"key":"sampleKey","values":
  [{"key":"insidesampleKey","value":2},{"key":"insideofinside","value":2}]},

{"key":"sampleKey2","values":[{"key":"insideSampleKey2","value":1}]},

{"key":"samplkey3","values":[{"key":"insideofsampleKey3","value":1}]}]

var values = sample.reduce((acc, item) => acc.concat(item.values.map(v=> v.value)),[]);
console.log(values);

Upvotes: 1

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

The easiest method is to use a flatMap over the array as below. You can use polyfill for browsers that don't support the same yet. Use MDN to learn more.

sample.flatMap(item => item.values.map(inner => inner.value))

Upvotes: 0

Related Questions