我如何获取这个对象和数组。
const data = {
type: "hello",
point: 1.8
};
const raw = [
{
x: [1, 2],
y: [-1.1, -1.2]
},
{
x: [14, 24],
y: [-1.14, 1.24]
}
];
然后将 data
对象中的项目“附加”到 raw
数组中的每个对象。期望的最终结果是;
const result = [
{
x: [1, 2],
y: [-1.1, -1.2],
type: "hello",
point: 1.8
},
{
x: [14, 24],
y: [-1.14, 1.24],
type: "hello",
point: 1.8
}
];
我尝试使用map
,但该对象适用于数组,然后我考虑使用Object.keys
,但没有运气。
最佳答案
使用map
进行传播:
const data = {type:"hello",point:1.8};
const raw = [{x:[1,2],y:[-1.1,-1.2]},{x:[14,24],y:[-1.14,1.24]}];
const result = raw.map(e => ({ ...e, ...data }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5 语法:
var data = {type:"hello",point:1.8};
var raw = [{x:[1,2],y:[-1.1,-1.2]},{x:[14,24],y:[-1.14,1.24]}];
var result = raw.map(function(e) {
return Object.assign({}, e, data);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }
关于javascript - 将对象中的静态元素附加到对象数组中的每个对象javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56513883/