简体   繁体   English

Javascript 合并键和值

[英]Javascript Merge keys and values

{Test1: 11, Test2: 25, Test3: 4, others: 5, others: 9, others: 11, others: 13, others: 27}

I am getting this object in return and my requirement is to show it like:我得到这个对象作为回报,我的要求是将它显示为:

{Test1: 11, Test2: 25, Test3: 4, others: 65}

Where 65 is the sum of all values with a others key.其中 65 是所有值与others键的总和。

Below is the code.下面是代码。

openTypeCaseChart.data.labels = $.map(countJson['types'], function(obj, index) {
    var retObj;
    if (index <= 2){
        retObj = obj['type_label'] + " " + obj['open'];
        return retObj;
    } else {
        total += obj['open']
        retObj = obj['type_label'] = "others"+ " " + total;
    }
    console.log("retObj: "+retObj);

}

I suppose you have input in this format:我想你已经输入了这种格式:

const countJson = {
  types: [
    {
      type_label: 'Test1',
      open: 11,
    },
    {
      type_label: 'Test2',
      open: 25,
    },
    {
      type_label: 'Test3',
      open: 4,
    },
    {
      type_label: 'Test4',
      open: 5,
    },
    {
      type_label: 'Test5',
      open: 9,
    },
    {
      type_label: 'Test6',
      open: 11,
    },
    {
      type_label: 'Test7',
      open: 13,
    },
    {
      type_label: 'Test8',
      open: 27,
    },
  ],
  // ...
};

Then you can use this function that takes your countJson object as an input and returns a string with keys less than index 2 with their original keys (Test1, Test2, Test3) and all items above those with their values summed and merged into a single key 'others':然后你可以使用这个函数,它将你的 countJson 对象作为输入并返回一个键小于索引 2 的字符串和它们的原始键(Test1、Test2、Test3)以及高于这些值的所有项,它们的值相加并合并为一个键'其他':

const mergeCounts = countJson => {
  const itemsObj = countJson.types
    .reduce((obj, item, i) => {
      const k = item.type_label;
      const v = item.open;

      // for all items after index 2, sum and merge them into a single key 'others'
      if (i > 2) {
        const othersValue = v + (obj['others'] || 0);

        return {
          ...obj,
          'others': othersValue,
        };
      }

      // for items up to index 2, return key value pairs
      return {
        ...obj,
        [item.type_label]: item.open
      };
    }, {})

  // At this point, you get:
  // itemsObj = { Test1: 11, Test2: 25, Test3: 4, others: 65 }

  return Object.keys(itemsObj)
    .map((k, i) => `${k} ${itemsObj[k]}`)
    .join(','); // this results: Test1 11,Test2 25,Test3 4,others 65
};

console.log(
  mergeCounts(countJson) // results: Test1 11,Test2 25,Test3 4,others 65
);

You can use for in loop for your requirement.您可以根据需要使用 for in 循环。 Example例子

for(let key in object)
{
  console.log(key +" "+object[key])
}

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

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