1

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']

3 Answers 3

4

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

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

Comments

2

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

4 Comments

Thanks for quick response! Flat Map does not look to be supported in IE :/ I'd like it to work on all browsers
@Michael you tagged this question with ecmascript-6
ah you're right! my mistake, this will work. thank you!
Alternative, straight from MDN
0

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

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.