gpt4 book ai didi

javascript - 用对象数组中的另一个属性替换键值

转载 作者:行者123 更新时间:2023-11-30 19:32:05 25 4
gpt4 key购买 nike

将数组与对象合并并返回一个包含所有属性的数组,该数组具有对象值数组或空值

let object = {
keys: {
test1: {label: "Test_1"},
test2: {label: "Test_2"},
test3: {label: "Test_3"}
}
}

let data = [{test1: "1", test2: "2", default:"123134" }, {test1: "1", test2: "2", default:"123134"}, {test1: "1", test3: "3"}, {test3: "3"}]

我期待下面的对象数组

let expectedArray = [{Test_1: "1", Test_2: "2", Test_3: null ,default:"123134" }, {Test_1: "1", Test_2: "2", Test_3: null,  default:"123134"}, {Test_1: "1", Test_3: "3", Test_2:null }, {Test_3: "3", Test_1: null, Test_2: null}]

试过下面的片段

let res = data.map(o => {
let obj = {}
let c = Object.keys(o).forEach(aa => {
obj[object.keys[aa].label] = o[aa]
})
return obj
})

感谢任何帮助

最佳答案

您可以替换对象的现有键并重建新对象。

var object = { keys: { test1: { label: "Test 1" }, test2: { label: "Test 2" }, test3: { label: "Test 3" } } },
data = [{ test1: "1", test2: "2", default: "123134" }, { test1: "1", test2: "2", default: "123134" }, { test1: "1", test3: "3" }, { test3: "3" }],
templates = Object.values(object.keys).map(({ label }) => ({ [label]: null })),
result = data.map(o => Object.assign(
{},
...templates,
...Object
.entries(o)
.map(([k, v]) => ({ [k in object.keys ? object.keys[k].label : k]: v }))
));

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

关于javascript - 用对象数组中的另一个属性替换键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328679/

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