0

I have an array of salesRecord, such as

const clientRecord = [
  {clientNumber: "3232",record: [{a:1, b:2},{a:3, b:4},{a:5, b:6}]},
  {clientNumber: "12345",record: [{a:7, b:8},{a:9, b:0}]},
]

I want to return an array of record objects form this array such as

const records = [
  {{a:1, b:2},{a:3, b:4},{a:5, b:6}}, 
  {{a:7, b:8},{a:9, b:0}}
]

How do I accomplish this in javascript. I want to avoid nested loops while implementing this.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Olasunkanmi
  • 323
  • 6
  • 18

2 Answers2

4

Use map() to extract the records arrays from each object.

const records = clientRecords.map(rec => rec.record);
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

The desired result you've written in the question is not a valid JS contruction:

const records = [
{{a:1, b:2},{a:3, b:4},{a:5, b:6}},
{{a:7, b:8},{a:9, b:0}}
]

You may have array of arrays, or array of all records, but in your example you have {{..}} construction with curly braces like object, but without any keys - that is not valid.

So, in order to get one of the valid options you can write the following code:

const clientRecord = [
{clientNumber: "3232",record: [{a:1, b:2},{a:3, b:4},{a:5, b:6}]},
{clientNumber: "12345",record: [{a:7, b:8},{a:9, b:0}]},
]

const records = clientRecord.map(x => x.record);

console.log(records); // [[{..}, {..}], [{..}], ... ]
Or, if you need to have each record being separate in the list, you can flat the array:

const clientRecord = [
{clientNumber: "3232",record: [{a:1, b:2},{a:3, b:4},{a:5, b:6}]},
{clientNumber: "12345",record: [{a:7, b:8},{a:9, b:0}]},
]

const records = clientRecord.map(x => x.record).flat();

console.log(records); // [{..},{..},{..}, ...]
Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
  • 2
    or `.flatMap()` could be used instead of map()+flat() which is designed to flatten the resulting mapped arrays into one resulting array – Nick Parsons Jul 25 '21 at 09:32