将数组与对象合并,并返回具有所有属性且对象值为null的数组
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
})
任何帮助表示赞赏
答案 0 :(得分:1)
您可以替换对象的现有键并重建新对象。
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; }