3 回答
TA贡献1812条经验 获得超5个赞
循环结束obj2。如果该key值是 的属性obj,则将相应的值复制到setValue对象的属性中,并将其压入结果。
obj = {
"name": "jack",
"age": 10,
"country": "india",
"state": "Delhi"
};
obj2 = [{key: "product", type="", value="", required="true", mandatory="true"},
{key: "sub-product", type="", value="", required="true", mandatory="true"},
{key: "name", type="text", value="", required="true", mandatory="true"},
{key: "age", type="text", value="[0-9]", required="true", mandatory="true"},
{key: "country", type="text", value="[a-z]", required="true", mandatory="true"},
{key: "state", type="text", value="[a-z]", required="true", mandatory="true"}];
var result = [];
obj2.forEach(o => {
if (o.key in obj) {
o.setValue = obj[o.key];
result.push(o);
}
});
console.log(result);
TA贡献1936条经验 获得超6个赞
您可以先使用过滤它hasOwnProperty,然后将其映射到设置setValue属性。这是实现:
var obj = { "name": "jack", "age": 10, "country": "india", "state": "Delhi" };
var obj2 =[{key: "product", type:"", value:"", required:"true", mandatory:"true"}, {key: "sub-product", type:"", value:"", required:"true", mandatory:"true"}, {key: "name", type:"text", value:"", required:"true", mandatory:"true"}, {key: "age", type:"text", value:"[0-9]", required:"true", mandatory:"true"}, {key: "country", type:"text", value:"[a-z]", required:"true", mandatory:"true"}, {key: "state", type:"text", value:"[a-z]", required:"true", mandatory:"true"}];
var result = obj2.filter(k=>obj.hasOwnProperty(k.key)).map(p=>({...p, setValue:obj[p.key]}));
console.log(result);
TA贡献1934条经验 获得超2个赞
你可以使用Array.prototype.flatmap来实现这个
const obj = {
"name": "jack",
"age": 10,
"country": "india",
"state": "Delhi"
}
const obj2 = [
{key: "product", type:"", value:"", required:"true", mandatory:"true"},
{key: "sub-product", type:"", value:"", required:"true", mandatory:"true"},
{key: "name", type:"text", value:"", required:"true", mandatory:"true"},
{key: "age", type:"text", value:"[0-9]", required:"true", mandatory:"true"},
{key: "country", type:"text", value:"[a-z]", required:"true", mandatory:"true"},
{key: "state", type:"text", value:"[a-z]", required:"true", mandatory:"true"}
]
const result = obj2.flatMap((entry) => {
if (obj[entry.key]) {
return {
...entry,
setValue: obj[entry.key],
}
}
return []
})
console.log(result)
添加回答
举报