简体   繁体   English

如何使用 javascript 从对象数组中执行添加相同键的对象值并返回唯一对象?

[英]How to perform addition of same keys' values of objects and return unique objects from array of objects using javascript?

am working on a task where I get a response consists of array of objects.我正在处理一项任务,其中我得到一个由对象数组组成的响应。

Now, I want to perform addition on some fields based on particular conditions and return new and unique array of objects without any duplicates.现在,我想根据特定条件对某些字段执行加法,并返回新的且唯一的对象数组,而不会出现任何重复。

Here is the response.这是回应。

let respData = [
  {
     "NEW": 0,
     "Working": 0,
     "Not Working": 2,
     "Broken": 0,
     "Location": "Karimnagar",
     "TotalPrice": 274500,
     "AssetsCount": 2,
     "AssetType": "Hardware Devices"
  },{
     "NEW": 1,
     "Working": 0,
     "Not Working": 0,
     "Broken": 0,
     "Location": "chennai",
     "TotalPrice": 4500,
     "AssetsCount": 1,
     "AssetType": "Undefined"
  },{
     "NEW": 0,
     "Working": 0,
     "Not Working": 0,
     "Broken": 0,
     "Location": "Undefined",
     "TotalPrice": 0,
     "AssetsCount": 1,
     "AssetType": "Undefined"
  },{
     "NEW": 1,
     "Working": 0,
     "Not Working": 0,
     "Broken": 0,
     "Location": "Karimnagar",
     "TotalPrice": 12500,
     "AssetsCount": 1,
     "AssetType": "Hardware Devices"
  },{
     "NEW": 0,
     "Working": 1,
     "Not Working": 0,
     "Broken": 0,
     "Location": "Karimnagar",
     "TotalPrice": 1200,
     "AssetsCount": 1,
     "AssetType": "Hardware Devices"
  }
]

Now am trying to add the integer values in objects if AssetType and Location are same.如果AssetTypeLocation相同,现在我尝试在对象中添加 integer 值。

If there are not matching results present, need to return them as it is.如果不存在匹配的结果,则需要按原样返回。

And after adding them, I need to return unique array of objects with all updated values.添加它们之后,我需要返回具有所有更新值的唯一对象数组。

I've tried with map and filter to get the result, but couldn't get the correct result.我已经尝试使用mapfilter来获得结果,但无法获得正确的结果。

This is the code I've tried.这是我尝试过的代码。

let respCopy = respData;
let finalObj = {}, testArray = [];

respCopy.forEach((copyData, i) => {
        respData.forEach((data, j) => {
            if(i !== j && copyData.AssetType === data.AssetType && copyData.Location === data.Location){
                assetConditions.forEach((condition, k) => {
                    if(copyData[condition.name]){
                        finalObj[condition.name] = copyData[condition.name] + data[condition.name];
                        finalObj["AssetType"] = copyData.AssetType;
                        finalObj["Location"] = copyData.Location;
                        copyData[condition.name] = 0;
                        data[condition.name] = 0;
                    }
                })
            }else if(i == j && copyData.AssetType === data.AssetType && copyData.Location === data.Location){
                assetConditions.forEach((condition, k) => {
                    if(copyData[condition.name]){
                        finalObj[condition.name] = copyData[condition.name];
                        finalObj["AssetType"] = copyData.AssetType;
                        finalObj["Location"] = copyData.Location;
                        copyData[condition.name] = 0;
                        data[condition.name] = 0;
                    }
                })
            }
        });
        testArray.push(finalObj);
    })

This is the expected result.这是预期的结果。

[
  {
     "NEW": 1,
     "Working": 1,
     "Not Working": 2,
     "Broken": 0,
     "Location": "Karimnagar",
     "TotalPrice": 288200,
     "AssetsCount": 4,
     "AssetType": "Hardware Devices"
  },{
     "NEW": 1,
     "Working": 0,
     "Not Working": 0,
     "Broken": 0,
     "Location": "chennai",
     "TotalPrice": 4500,
     "AssetsCount": 1,
     "AssetType": "Undefined"
  },{
     "NEW": 0,
     "Working": 0,
     "Not Working": 0,
     "Broken": 0,
     "Location": "Undefined",
     "TotalPrice": 0,
     "AssetsCount": 1,
     "AssetType": "Undefined"
  }
]

Code I've tried in Codepen我在 Codepen 中尝试过的代码

Is there anything am making mistakes in getting the result?得到结果有什么错误吗?

This type of issues can be easily solved using a dictionary object as a proxy.使用字典 object 作为代理可以轻松解决此类问题。

You have to define the object's keys as your unique identifier (in your case a concatenation of AssetType and Location values) then map them to the objects you want to create a unique array of.您必须将对象的键定义为您的唯一标识符(在您的情况下是AssetTypeLocation值的串联),然后将 map 定义为您想要创建唯一数组的对象。

Eventually you'll want to return the Object.values() of your dictionary object:最终你会想要返回你的字典 object 的Object.values()

 const arrayWithDuplicates = [{ key1: 1, key2: 2, foo: 1 }, { key1: 1, key2: 2, foo: 2 }, // Note the two first elements have identical keys { key1: 3, key2: 2, foo: 3 }, ]; function getDictKey(element) { // This can obviously be implemented otherwise const { key1, key2 } = element; return `${key1}_${key2}`; } const dictionary = {}; arrayWithDuplicates.forEach((element) => { const key = getDictKey(element); if (dictionary[key]) { dictionary[key].foo += element.foo; } else { dictionary[key] = element; } }); const arrayWithoutDuplicates = Object.values(dictionary); console.log(arrayWithoutDuplicates);

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

相关问题 如何从对象数组中获取具有特定键的唯一值的对象? - How to get objects with unique values for specific keys from array of objects? 如何通过添加数字从对象数组中获取唯一值 - how to get unique values from array of objects with addition of numbers 如何在对象数组中获取具有唯一值的键? (JavaScript) - How can I get keys with unique values in an array of objects? (JavaScript) Javascript - 仅返回对象数组中的唯一值 - Javascript - Return only unique values in an array of objects javascript从对象数组中提取键的相同值 - javascript extract same values of keys from array of objects 如何将键和零浮点值附加到对象数组中的对象? -Javascript - How to append keys and zero float values to objects in array of objects ? - Javascript Javascript对象数组和唯一值 - Javascript Array of Objects and Unique Values Javascript:如何从对象数组中获取分配给同一属性的唯一值列表? - Javascript: How to get a unique list of values assigned to the same property from an array of objects? 使用JavaScript将唯一对象插入对象数组? - Inserting unique objects into array of objects using javascript? 如何使用另一个对象数组的键和 arrays 数组中的值来构造对象数组? - How to construct an array of objects by using the keys of another array of objects and values from the array of arrays?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM