简体   繁体   English

如何将值从数组添加到对象?

[英]How can I add values from an array to an object?

I've got an array : 我有一个数组:

let array = ["1#2","2#2","32#1","43#3","44#4","1#1","54#2","1#1"];

I've got a RegExp (/(\\d+)#(\\d+)/g) and could .exec() to the one of the group; 我有一个RegExp (/(\\d+)#(\\d+)/g) ,可以将.exec()移到该组中的一个。 On this RegExp I've got two groups of digits. 在此RegExp上,我有两组数字。

If ("key"/ first group) equal we sum value of this ("key" first group) . 如果(“钥匙” /第一组)(“钥匙”第一组)的等于我们总和值。

How can I get this answer: 我如何获得此答案:

let answer = [
    { key: 1, value: 4 },     <==sum value of equal keys
    { key: 2, value: 2 },
    { key: 32, value: 1 },
    { key: 43, value: 3 },
    { key: 44, value: 4 },
    { key: 54, value: 2 } 
];

I'm trying to do this like : 我正在尝试这样做:

let itemObject = {
    key: '',
    value: ''
}

array.map((item) => {
        let itemNumber = RegExp.exec(item);
        itemObject.key = itemNumber[1];
        itemObject.value = itemNumber[2];
        this.emptyArray.push(itemObject);
      })

But this not working ... and I don't know what to do. 但这不起作用...而且我不知道该怎么办。

You don't have to use regex here, you can use split method to get keys and values. 您不必在这里使用正则表达式,可以使用split方法获取键和值。 Additionally you can use reduce to get the result: 另外,您可以使用reduce获得结果:

  let array = ["1#2","2#2","32#1","43#3","44#4","1#1","54#2","1#1"]; let answer = array.reduce((arr, curr)=> { let [key, value] = curr.split('#'); let existing = arr.find(x => x.key === +key); if(existing){ existing.value += +value; } else { arr.push({key:+key, value: +value}); } return arr; }, []); console.log(answer); 

You could take a map and check if the key and value is equal. 您可以拍一张地图,检查键和值是否相等。 Then add the actual value. 然后加上实际值。

 var array = ["1#2","2#2","32#1","43#3","44#4","1#1","54#2","1#1"], result = Array.from( array .reduce( (m, s) => (([k, v]) => m.set(k, (m.get(k) || 0) + v))(s.split('#').map(Number)), new Map ) .entries(), ([key, value]) => ({ key, value }) ); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

why don't you iterate over array, split on # and take the first value as key and second as its corresponding value and put them in a hash map. 为什么不遍历数组,在#上分割,将第一个值作为键,第二个作为其对应值,然后将它们放入哈希映射。 (if you are sure # is used as splitter always). (如果您确定始终将#用作拆分器)。

An alternative is splitting by # and using the function reduce to group the objects. 另一种方法是用#分割,然后使用函数reduce来对对象进行分组。

 let array = ["1#2","2#2","32#1","43#3","44#4","1#1","54#2","1#1"]; let result = Object.values(array.reduce((a, c) => { let [key, value] = c.split('#'), accumKey = key + '|' + value, currentValue = key === value ? value : 0; (a[accumKey] || (a[accumKey] = {key, value: 0})).value += Number(value); return a; }, {})); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM