[英]How to transform an array of objects with the same property name into the object in which value is concatenated from values in a given array? JS
I have an array of objects which looks like this:我有一个看起来像这样的对象数组:
const arr = [
{integer: "3"},
{integer: "500"}
]
As a result i want to get the object that looks like this: mergedObj = {digits: "3500"}
结果我想得到看起来像这样的对象:
mergedObj = {digits: "3500"}
I tried to use reduce, but it seems that i'm doing something wrong.我尝试使用reduce,但似乎我做错了什么。 Here is my code:
这是我的代码:
var mergedObj = arr.reduce((acc, obj) => {
acc["digits"] = [acc[obj.integer]].concat(obj.integer).join("");
return acc;
}, {});
Here is the result of what i'm getting:这是我得到的结果:
"Object is", [object Object] {
digits: "500"
}
The problem is that i'm missing the first part of my digit.问题是我缺少数字的第一部分。 Please help me!
请帮我! Thank you in advance!
先感谢您!
Use Array.map()
to create an array of integer
, and then join.使用
Array.map()
创建一个integer
数组,然后加入。 Assign to digits
property of a new object:分配给新对象的
digits
属性:
const arr = [ {integer: "3"}, {integer: "500"} ] const result = { digits: arr.map(o => o.integer).join('') }; console.log(result);
You almost got this.你几乎得到了这个。 The
[acc[obj.integer]]
part should be [acc.digits]
. [acc[obj.integer]]
部分应该是[acc.digits]
。 Anyway, you can do it much simpler:无论如何,你可以做得更简单:
const arr = [ {integer: "3"}, {integer: "500"} ] var mergedObj = arr.reduce((acc, obj) => { acc.digits += obj.integer; return acc; }, { digits: '' }); console.log(mergedObj);
Try this below :试试这个:
const arr = [
{integer: "3"},
{integer: "500"}
]
let output = {'digits':''};
arr.map(function (item) {
output['digits'] += item['integer']
});
console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.