[英]How to join two or more objects that are in an array? Javascript
I want to join two objects that are inside an array:我想加入一个数组中的两个对象:
const test = [{name: ""}, {age: ""}, {nac: ""}];
I need it to look like this:我需要它看起来像这样:
const test2 = [{name: "", age: "", nac: ""}];
I tried with: Object.assign () but I can't get it.我试过: Object.assign () 但我无法得到它。
Any other ideas I can try?我可以尝试其他任何想法吗?
You can use Object.assign
with spread syntax .您可以将
Object.assign
与扩展语法一起使用。
const test = [{name: ""}, {age: ""}, {nac: ""}]; const test2 = [Object.assign({}, ...test)]; console.log(test2);
You can use array.prototype.reduce
function that will be useful when reducing an array to a single value.您可以使用
array.prototype.reduce
函数,该函数在将数组减少为单个值时会很有用。 I have given example below我在下面给出了例子
const test = [{name: ""}, {age: ""}, {nac: ""}];
const reducer = (accumulator, currentValue) => {
for (var key in currentValue) {
accumulator[key] = currentValue[key];
}
return accumulator;
};
var finalObj = test.reduce(reducer, {});
console.log(finalObj);
console.log([finalObj]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.