Michael
Michael

Reputation: 443

Map array object values to new array

I have an array of objects that contain a property called rates and inside each objects rates array are id's (among other properties, not shown here for simplicity). How can I map these id's to a new array so that I have a record of all id's returned in all objects rates?

 const sampleResponse = [
   {
     id: '123',
     rates: [{ id: '123' }, { id: '456' }]
   },
   {
     id: '456',
     rates: [{ id: '789' }, { id: 'ABC' }]
   },
   {
     id: '789',
     rates: [{ id: 'DEF' }, { id: 'GHI' }]
   }
 ]

Expected Result

const result = ['123', '456', '789', 'ABC', 'DEF', 'GHI']

Upvotes: 1

Views: 209

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Using forEach and destructuring

const rateIds = (arr, output = []) => {
  arr.forEach(({ rates }) => rates.forEach(({ id }) => output.push(id)));
  return output;
};

const sampleResponse = [
  {
    id: "123",
    rates: [{ id: "123" }, { id: "456" }],
  },
  {
    id: "456",
    rates: [{ id: "789" }, { id: "ABC" }],
  },
  {
    id: "789",
    rates: [{ id: "DEF" }, { id: "GHI" }],
  },
];

console.log(rateIds(sampleResponse));

Upvotes: 0

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14208

You can use .concat() combines with .map() to achieve it.

const sampleObject = [
 {
   id: '123',
   rates: [{ id: '123' }, { id: '456' }]
 },
 {
   id: '456',
   rates: [{ id: '789' }, { id: 'ABC' }]
 },
 {
   id: '789',
   rates: [{ id: 'DEF' }, { id: 'GHI' }]
 }];
 
 let result = [];
 for(let item of sampleObject){
    result = result.concat(item.rates.map(r => r.id));
 } 
console.log(result);

Or .reduce like this way

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

const sampleObject = [
 {
   id: '123',
   rates: [{ id: '123' }, { id: '456' }]
 },
 {
   id: '456',
   rates: [{ id: '789' }, { id: 'ABC' }]
 },
 {
   id: '789',
   rates: [{ id: 'DEF' }, { id: 'GHI' }]
 }];
 
 const result = sampleObject.reduce((acc, x) => acc.concat(x.rates.map(r => r.id)), []);
 console.log(result);

Upvotes: 4

phi-rakib
phi-rakib

Reputation: 3302

You could use Array.prototype.flatMap() with Array.prototype.map().

const sampleObject = [
  {
    id: '123',
    rates: [{ id: '123' }, { id: '456' }],
  },
  {
    id: '456',
    rates: [{ id: '789' }, { id: 'ABC' }],
  },
  {
    id: '789',
    rates: [{ id: 'DEF' }, { id: 'GHI' }],
  },
];
const ret = sampleObject.flatMap((x) => x.rates.map((y) => y.id));
console.log(ret);

Upvotes: 2

Related Questions