[英]Join values from multiple objects with key based on array values - Javascript
I need to create a new object with keys and values based on array of keys from another object.我需要创建一个新的 object,其键和值基于另一个 object 的键数组。 I have two Objects with the following structure:
我有两个具有以下结构的对象:
const parentObject = {P1:['C1','C2','C3','C4'], P2:['C5','C6']};
const values = {C1: "value", C2: "value", C3: "value",C4: "value", C5: "value",C6: "value"}
The result I expect is:我期望的结果是:
const result = {P1: {C1: "value", C2: "value", C3: "value", C4: "value"},
P2: {C5: "value",C6: "value"}}
What I tried:我尝试了什么:
let result = {}
Object.entries(parentObject).map(([key, value]) => {
value.map(i => {
let keysAndValues = { [key]: { [i]: values[i] } };
result = Object.assign(keysAndValues)
})
})
The result of my code is only the last parent and value, but I need all of them.我的代码的结果只是最后一个父级和值,但我需要所有这些。
The keys and values is a result from a database so it changes all the time.
键和值是数据库的结果,因此它一直在变化。
You can use您可以使用
const parentObject = {P1:['C1','C2','C3','C4'], P2:['C5','C6']}; const values = {C1: "value", C2: "value", C3: "value",C4: "value", C5: "value",C6: "value"} const result = Object.fromEntries( Object.entries(parentObject).map(([key, value]) => [ key, value.reduce((p, c) => (p[c] = values[c], p), {}) ]) ); console.log(result);
As a sidenote, in devtool global scope, there is already a values
(also in browsers other than chrome, eg FF), which would clash, but there is no problem, if it's inside some other scope, or just not in the console, which is probably the case for you.作为旁注,在devtool global scope中,已经有一个
values
(也在chrome以外的浏览器中,例如FF),这会发生冲突,但没有问题,如果它在其他一些scope中,或者只是不在控制台中,这可能是你的情况。
You could take a recursive function which works with array, objects an just a promitive for getting the value.您可以采用与数组一起使用的递归 function ,对象只是获取值的促进因素。
const fill = pattern => Array.isArray(pattern)? pattern.map(fill): pattern && typeof pattern === 'object'? Object.fromEntries(Object.entries(pattern).map(([k, v]) => [k, fill(v)])): values[pattern], pattern = { P1: ['C1', 'C2', 'C3', 'C4'], P2: ['C5', 'C6'] }, values = { C1: "value", C2: "value", C3: "value", C4: "value", C5: "value", C6: "value" }, result = fill(pattern); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.