sqldoug sqldoug - 7 months ago 28
Javascript Question

New array of objects based on an array inside an object?

need to create a shallow array of objects based on the elements of an array that is an object's value:

var obj = {
a: 1,
b: 'x',
c: 'z',
d: ['rr', 'qq']

var rec = [];

obj.d.forEach(function(e, i) {
d: e


But of course this only gets me

[ { d: 'rr' }, { d: 'qq' } ]

How to get to this in a new array of objects? -->

[ { a: 1,
b: 'x',
c: 'z',
d: 'rr' },
{ a: 1,
b: 'x',
c: 'z',
d: 'qq' } ]


The easiest way to get the desired result would be to use the map function (which maps elements of one array to a new array using a given mapping function). You can then create new objects re-using a, b, and c from the original object and d from the mapping function parameters:

var rec = obj.d.map(function(r) {
  return { 
    a: obj.a, 
    b: obj.b, 
    c: obj.c, 
    d: r