1

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

4 Answers 4

1

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

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

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

Comments

1

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);

Comments

0

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))

Comments

0

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));

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.