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

因此,我的状态如下所示:

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

最佳答案

您可以通过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)

关于javascript - 将状态数组值转换为键值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56179966/

10-09 16:58