Reputation: 409
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' } ]
Upvotes: 0
Views: 81
Reputation: 409
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);
Upvotes: 0
Reputation: 245399
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
};
});
Upvotes: 4
Reputation: 271
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.
Upvotes: 1