[英]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) {
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' } ]
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). 获得期望结果的最简单方法是使用map
函数(使用给定的映射函数将一个数组的元素映射到新数组)。 You can then create new objects re-using a
, b
, and c
from the original object and d
from the mapping function parameters: 然后,可以使用原始对象的a
, b
和c
以及映射函数参数的d
来创建新对象:
var rec = obj.d.map(function(r) {
return {
a: obj.a,
b: obj.b,
c: obj.c,
d: r
};
});
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. 但是属性a,b,c不能是对象。 Otherwise each item in the rec array will have the same reference. 否则,rec数组中的每个项目都将具有相同的引用。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.