计算对象数组上的所有值-javascript

时间:2019-03-21 07:02:41

标签: javascript arrays json object

我需要计算对象数组上的每个值,所需的输出应如下所示

[{
    "question": "question1",
    "USA": 2
  }, {
    "question": "question1",
    "AUS": 1
  },

  {
    "question": "question2",
    "item1": 2
  },

  {
    "question": "question2",
    "item1,item2": 1
  }, {
    "question": "question4",
    "3": 1
  }, {
    "question": "question4",
    "2": 1
  }
]

下面是我需要转换为以上输出的输入。我不知道如何处理无问题,并且当一个问题有2个答案时也有问题。样本输入

[{"question1":"USA","question2":["item1"],"question4":2}, 
{"question1":"USA","question2":["item1"],"question4":3}, 
{"question1":"AUS","question2":["item1","item2"]}];

let arr=[{"question1":"USA","question2":["item1"],"question4":2},{"question1":"USA","question2":["item1"],"question4":3},{"question1":"AUS","question2":["item1","item2"]}];
//console.log(arr);



function solve(list){
    var map = new Map();
    var entry = null;
    for(var item of list){
        if(!map.has(item.question1))
            map.set(item.question1, {question:'question1'});

            entry = map.get(item.question1);

        if(entry.hasOwnProperty(item.question1))
            entry[item.question1] = entry[item.question1] + 1;
        else
            entry[item.question1] = 1;
            
         
          if(!map.has(item.question2))
            map.set(item.question2, {question: 'question2'});

            entry = map.get(item.question2);

        if(entry.hasOwnProperty(item.question2))
            entry[item.question2] = entry[item.question2] + 1;
        else
            entry[item.question2] = 1;
         
    }
    return Array.from(map.values());
}
console.log(solve(arr))

3 个答案:

答案 0 :(得分:3)

您可以采用对象或任何喜欢的数据结构以嵌套样式支持键/值结构,然后首先收集所有项,然后重新整理收集的树。

此方法使用对象,因为键是字符串,这对于将数组用作键很重要。对于这种用例,这加上逗号就足够了。

you are automatically on the newest commit of the chosen branch
var data = [{ question1: "USA", question2: ["item1"], question4: 2 }, { question1: "USA", question2: ["item1"], question4: 3 }, { question1: "AUS", question2: ["item1", "item2"] }],
    hash = data.reduce((hash, o) => {
        Object.entries(o).forEach(([question, value]) => {
            var sub = hash[question] = hash[question] || Object.create(null);
            sub[value] = sub[value] || { question, [value]: 0 };
            sub[value][value]++;
        });
        return hash;
    }, Object.create(null)),
    result = Object.values(hash).reduce((r, sub) => [...r, ...Object.values(sub)], []);

console.log(result);

答案 1 :(得分:1)

首先,使用reduce获取国家/地区。然后,对其余部分使用嵌套的forEach循环:

const input = [{"question1":"USA","question2":["item1"],"question4":2}, 
{"question1":"USA","question2":["item1"],"question4":3}, 
{"question1":"AUS","question2":["item1","item2"]}];
const countriesOutput = input.reduce((acc, curr) => {
  if (!acc.some(e => e[curr.question1])) {
    acc.push({ question: "question1", [curr.question1]: 1 });
  } else {
    acc.find(e => e[curr.question1])[curr.question1]++;
  }
  return acc;
}, []);
let questionsOutput = [];
input.forEach(item => {
  Object.keys(item).forEach(key => {
    if (key != "question1") {
      if (Array.isArray(item[key])) {
        questionsOutput.push({ question: key, [item[key].join(",")]: 1 });
      } else {
        questionsOutput.push({ question: key, [item[key]]: 1 });
      }
    }
  });
});
const finalOutput = [...countriesOutput, ...questionsOutput];
console.log(finalOutput);
.as-console-wrapper { max-height: 100% !important; top: auto; }

答案 2 :(得分:1)

只需使用字典(例如Object)汇总输入并跟踪重复项即可。名称/值对的“名称”可以通过将问题和答案与某些定界符结合使用来唯一标识。

const input = [{
    "question1": "USA",
    "question2": ["item1"],
    "question4": 2
  },
  {
    "question1": "USA",
    "question2": ["item1"],
    "question4": 3
  },
  {
    "question1": "AUS",
    "question2": ["item1", "item2"]
  }
];



//Sum the input to an array which we can easily search for duplciates
var repeatCounter = {};

input.forEach(objItem => {

  Object.keys(objItem).forEach(propItem => {


    //Get the counter and the string
    var s = `${propItem}-${objItem[propItem]}`;
    var c = repeatCounter[s] || 0;

    //Modify it or introduce it if absent
    repeatCounter[s] = c + 1;


  })

})




var output = Object.keys(repeatCounter).map(element => {

  var ret = {'question': element.split('-')[0]}

  ret[element.split('-')[1]] = repeatCounter[element];
  
  return ret;

})


   console.log(output);
.as-console-wrapper {
  max-height: 100% !important;
}

需要细心的调整,例如加强定界符,将多个字符串转换为数组项(如问题所示)。