将所有对象加到一个对象数组中

时间:2019-05-21 20:53:15

标签: javascript arrays

我有一个对象数组,类似于下一个示例:

let tryout = [
  {text: 1, video: 1, photo: 2, song: 1},
  {text: 2, video: 3, photo: 1},
  {text: 4, video: 2, photo: 2},
]

我想添加它们以最终获得这种对象:

let newObjet = {
  text: 7,
  video: 6,
  photo: 5,
  song: 1
}

什么是最好的方法?我正在尝试reduce(),但是我得到的只是对象keys的合并,而values却没有加起来。

重要的一点是,我不知道keys将在对象内部。

这是我的尝试(未按预期工作):

var resultObject = tryout.reduce(function(result, currentObject)
{
    for (var key in currentObject)
    {
        if (currentObject.hasOwnProperty(key)) {
            result[key] = currentObject[key];
        }
    }

    return result;
}, {});

1 个答案:

答案 0 :(得分:2)

一种解决方案是将Array.reduce()Object.entries()组合使用

let tryout = [
  {text: 1, video: 1, photo: 2, song: 1},
  {text: 2, video: 3, photo: 1},
  {text: 4, video: 2, photo: 2}
]

let res = tryout.reduce((acc, obj) =>
{
    Object.entries(obj).forEach(([k, v]) =>
    {
        acc[k] = (acc[k] || 0) + v;
    });

    return acc;
}, {});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

与您的代码有关,您在if句子上遇到了问题,而不是检查下一个条件:

if (currentObject.hasOwnProperty(key)) {...}

每次使用true时(在遍历同一对象的循环内),将为result.hasOwnProperty(key),您需要检查是否key以决定是否将数字添加到该key的先前存储结果,或将其分配给let tryout = [ {text: 1, video: 1, photo: 2, song: 1}, {text: 2, video: 3, photo: 1}, {text: 4, video: 2, photo: 2} ] var resultObject = tryout.reduce(function(result, currentObject) { for (var key in currentObject) { if (result.hasOwnProperty(key)) result[key] += currentObject[key]; else result[key] = currentObject[key]; } return result; }, {}); console.log(resultObject);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
WITH CTE AS (
SELECT f.FacilityID as 'FID'
     , COUNT (DISTINCT f.PhoneTypeID) as 'Ptypes'
     , COUNT (DISTINCT f.PhoneID) as 'Pnumbers'
FROM dbo.FacilityPhones as f
GROUP BY f.FacilityID 
HAVING COUNT(DISTINCT f.PhoneTypeID)<>COUNT(DISTINCT f.PhoneId))

SELECT *
FROM dbo.FaclityPhones FP
INNER JOIN dbo.Phones as ph
        ON FP.PhoneID = ph.PhoneID
WHERE EXISTS (SELECT 1 
              FROM CTE 
              WHERE FID = FP.FacilityID)