0

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) {
  rec.push({
    d: e
  })
});

console.log(rec);

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' } ]
1
  • If I understand you correctly: for however many array elements, a new object within the new array Commented Aug 18, 2016 at 21:02

3 Answers 3

4

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 
  };
});
Sign up to request clarification or add additional context in comments.

2 Comments

Please explain your answers
Thanks so much -- I think it should be }); at the end?
1
obj.d.forEach(function(e) {
    var item = {};

    Object.keys(obj).forEach(function(key) {
        item[key] = obj[key];
    });

    item.d = e;

    rec.push(item);
});

But properties a, b, c can't be objects. Otherwise each item in the rec array will have the same reference.

Comments

0

Alternately, this works, but it is quite ugly:

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

var arr = [];

Object.keys(o).forEach(function(k) {
    var val = o[k];
    if (Array.isArray(val)) {
        val.forEach(function(j) {
        arr.push({[k] : j});
        });
    }
});

arr.forEach(function(obj) {
    for (var p in o) {
        var val = o[p];
        if (!Array.isArray(val)) {
        obj[p] = val
        }
    }
});

console.log(arr);

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.