gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:13:15 25 4
gpt4 key购买 nike

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

所以,我的状态如下所示:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com