1

We have an array like

const arr = [{
    name: 'foo',
    age: 23,
    id: [1, 2]
}, {
    name: 'bar',
    age: 24,
    id: [3, 4]
}, {
    name: 'baz',
    age: 24,
    id: 5
}];

If object has array of ids then a new object should be added to the array

expected

const newArry = [{
    name: 'foo',
    age: 23,
    id: 1,
}, {
    name: 'foo',
    age: 23,
    id: 2
}, {
    name: 'bar',
    age: 24,
    id: 3
}, {
    name: 'bar',
    age: 24,
    id: 4
}, {
    name: 'baz',
    age: 24,
    id: 5
}]

anyone knows better way to do. Please help!!!

3 Answers 3

7

You can make use of flatMap for this. First you will check if the id is of type array, if so then apply map on it and return the appropriate value.

const arr = [{name: 'foo', age: 23, id: [1,2]}, {name: 'bar', age: 24, id: [3,4]}, {name: 'baz', age: 24, id: 5}];

const result = arr.flatMap(e=>Array.isArray(e.id) ? e.id.map(id=>({...e,id})) : e);

console.log(result);

However, check the browser compatibility for flatMap here. As an alternate you can make use of reduce method.

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

Comments

0

You can use array#reduce and push each id for array id and simply add object for string id.

const arr = [{name: 'foo', age: 23, id: [1,2]}, {name: 'bar', age: 24, id: [3,4]}, {name: 'baz', age: 24, id: 5}],
      result = arr.reduce((r, o) => {
        if(Array.isArray(o.id)) {
          o.id.forEach(id => r.push({ ...o, id }));
        } else {
          r.push(o);
        }
        return r;
      }, []);
console.log(result);

Comments

0

Tweeked array.forEach for the implementation. Hope this will be helpful.

const arr = [{
    name: 'foo',
    age: 23,
    id: [1, 2]
}, {
    name: 'bar',
    age: 24,
    id: [3, 4]
}, {
    name: 'baz',
    age: 24,
    id: 5
}];

const newArry = [];
arr.forEach(item => {
  if (typeof(item.id) === 'number') {
    newArry.push({
      name: item.name,
      age: item.age,
      id: item.id,
    })
  } else {
    item.id.forEach( idItem => {
      newArry.push( {
        name: item.name,
        age: item.age,
        id: idItem,
      })
    })
  }
})

console.log(newArry);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.