将状态数组值转换为键值对

时间:2019-05-17 05:09:04

标签: javascript json reactjs state

我有一个状态对象数组。我想将数组内的值转换为键值对

所以,我的状态如下:

0: {emp_code: "a001", company_code: "company_a", name: "abx", details: Array(3), details_dtypes: Array(3)}
1: {emp_code: "b002", company_code: "company_b", name: "xbz ", details: Array(2), details_dtypes: Array(2)}
//and so on adding other values to the array

我想将emp-code和company_code转换为键值对,并像JSON对象一样显示; 因此,JSON输出看起来像这样:

{
emp_and_company:
{
  "company_a" : ["a001","a002"],
  "company_b" : ["b002","b003"]
}
}

所以我只想将company_code作为键,将值作为emp_code

2 个答案:

答案 0 :(得分:5)

您可以通过Array.reduce简洁地完成此操作:

const data = [{ emp_code: "a001", company_code: "company_a", name: "abx", details: [], details_dtypes: [] }, { emp_code: "b002", company_code: "company_b", name: "xbz ", details: [], details_dtypes: [] }, { emp_code: "a002", company_code: "company_a", name: "xbz ", details: [], details_dtypes: [] }, { emp_code: "b003", company_code: "company_b", name: "xbz ", details: [], details_dtypes: [] } ]

let result = data.reduce((r,c) => 
  (r[c.company_code] = [...(r[c.company_code] || []), c.emp_code]) && r, {})

console.log(result)

这是一个更具可读性的版本:

const data = [{ emp_code: "a001", company_code: "company_a", name: "abx", details: [], details_dtypes: [] }, { emp_code: "b002", company_code: "company_b", name: "xbz ", details: [], details_dtypes: [] }, { emp_code: "a002", company_code: "company_a", name: "xbz ", details: [], details_dtypes: [] }, { emp_code: "b003", company_code: "company_b", name: "xbz ", details: [], details_dtypes: [] }]

let result = data.reduce((acc, obj) => {
  acc[obj.company_code] = [...(acc[obj.company_code] || []), obj.emp_code]
  return acc
}, {})

console.log(result)

答案 1 :(得分:-1)

var output = {};
array.forEach((data) => {
   var prev = output[data['company_code']] || [];
   prev.push(data['emp_code']);
   output[data['company_code']] = prev;
});