目前我在 JSON 对象中嵌套了数组。我想定义
的键和值如果缺少此键之一,则需要填充为默认键和值,如预期输入中所示。 谁能帮忙用 JavaScript 实现这一点吗?
电流输入
{
"data": [{
"name": "John",
"contact": {
"phone": "987-654-3210",
"email": "[email protected]"
},
"address": {
"city": "Berlin",
"country": "Germany"
}
}]
}
预期输入
{
"data": [{
"name": "John",
"contact": {
"phone": "987-654-3210",
"email": "[email protected]",
"fax" : "",
"website" : ""
},
"address": {
"city": "Berlin",
"country": "Germany",
"house_number :"",
"street name" :""
}
}]
}
如果您不介意改变原始数组,这里有一个解决方案:
const templates = {
contact: {
"phone": "",
"email": "",
"fax": "",
"website": ""
},
address: {
"city": "",
"country": "",
"house_number": "",
"street name": ""
}
}
source.data.forEach(entry => Object.entries(templates).forEach(([key, template]) => {
entry[key] ||= {};
Object.entries(template).forEach(([k, v]) => {
entry[key][k] ||= v;
});
}));
const source = {
"data": [{
"name": "John",
"contact": {
"phone": "987-654-3210",
"email": "[email protected]"
},
"address": {
"city": "Berlin",
"country": "Germany"
}
}, {
"name": "Bob",
"contact": {
"phone": "123-456-7890",
"fax": "9876-5432",
"website": "bob.example.com"
},
"address": {
"city": "NYC",
"country": "USA",
"house_number": "701A"
}
}]
};
const templates = {
contact: {
"phone": "",
"email": "",
"fax": "",
"website": ""
},
address: {
"city": "",
"country": "",
"house_number": "",
"street name": ""
}
}
source.data.forEach(entry => Object.entries(templates).forEach(([key, template]) => {
entry[key] ??= {};
Object.entries(template).forEach(([k, v]) => {
entry[key][k] ??= v;
});
}));
console.log(source);