gpt4 book ai didi

javascript - 根据 JSON 的值和 JSON 数组的键合并一个 JSON 和 JSON 数组

转载 作者:搜寻专家 更新时间:2023-11-01 00:29:51 25 4
gpt4 key购买 nike

我想尝试通过组合这两个 JSON 和 JSON 数组在 Node 中创建一个 JSON 数组

`var template = {
"key1": "value1",
"key3": "value3",
"key4": "value3",
"key6": "Dummy Value1"
};
var data = [
{
"value1": "1",
"value2": "2",
"value3": "3"
},
{
"value1": "11",
"value2": "12",
"value3": "13"
},
{
"value1": "21",
"value2": "22",
"value3": "23"
}
];`

我需要结果 JSON 是这样的

var result = [
{
"key1": "1",
"key3": "3",
"key4": "3",
"key6": "Dummy Value1"
},
{
"key1": "11",
"key3": "13",
"key4": "13",
"key6": "Dummy Value1"
},
{
"key1": "21",
"key3": "23",
"key4": "23",
"key6": "Dummy Value1"
}
]

在我的例子中,JSON 数组中大约有 40 个键,模板 JSON 中大约有 25 个键,所以我也在为此寻找优化的解决方案。任何人都可以帮助我吗?

最佳答案

使用Array#mapArray#reduce方法。

// iterate over the array
var res = data.map(function(o) {
// get the property names array and iterate to generate
// result object
return Object.keys(template).reduce(function(obj, k) {
// define property based on the array element object has
// the prefered property or not
obj[k] = o.hasOwnProperty(template[k]) ? o[template[k]] : template[k];
// return the object reference
return obj;
// set initial value as an empty object which is used as
// the new array element
}, {});
});

var template = {
"key1": "value1",
"key3": "value3",
"key4": "value3",
"key6": "Dummy Value1"
};
var data = [{
"value1": "1",
"value2": "2",
"value3": "3"
}, {
"value1": "11",
"value2": "12",
"value3": "13"
}, {
"value1": "21",
"value2": "22",
"value3": "23"
}];

var res = data.map(function(o) {
return Object.keys(template).reduce(function(obj, k) {
obj[k] = o.hasOwnProperty(template[k]) ? o[template[k]] : template[k];
return obj;
}, {});
});

console.log(res);

关于javascript - 根据 JSON 的值和 JSON 数组的键合并一个 JSON 和 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40758437/

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