我有一个 json 对象 (firstObj) 它可以嵌套,我有第二个对象包含键/值对。我想通过匹配值将第二个对象的值替换为第一个对象的值并执行它的操作。
let firstObj = {
amount_money: {
amount: {
mapped_field: 'payment_amt',
operation: '/10'
},
currency: {
mapped_field: 'payment_cur',
operation: null
}
},
source_id: {
mapped_field: 'request_id',
operation: null
},
ship: [
{ mapped_field: 'ship_country[0]', operation: null },
{ mapped_field: 'ship_country[1]', operation: null }
]
};
我的第二个对象
let secondObj = {
payment_amt: 100,
payment_cur: 'USD',
request_id: '123ASD',
ship_country: [
{ code: 'USA', Title: 'America' },
{ code: 'UK', Title: 'England' }
]
};
我想要这样的东西
{
amount_money: {
amount: 10
currency: 'USD'
},
source_id: '123ASD',
ship: [ {America: 'USA'}, {England: 'UK'}]
}
非常感谢您的帮助, 谢谢!
最佳答案
更新
如果你不知道有多少个嵌套 Node 。有一个使用递归的更全面的解决方案。
解决方法如下:
const firstObj = {
source_name: {
mapped_field: 'request_name',
operation: null,
},
amount_money: {
amount: {
mapped_field: 'payment_amt',
operation: '/10',
},
currency: {
mapped_field: 'payment_cur',
operation: null,
},
},
source_id: {
mapped_field: 'request_id',
operation: null,
},
nested: {
nested: {
nested: {
nested: {
mapped_field: 'mapping_nested',
operation: null,
},
},
},
},
};
let secondObj = {
payment_amt: 100,
payment_cur: 'USD',
request_id: '123ASD',
request_name: 'Dollar',
mapping_nested: 'Hello',
};
const procedure = (firstObj, parentObj = {}, nestedObj = {}) => {
for (const [key, value] of Object.entries(firstObj)) {
if (value.hasOwnProperty('mapped_field') && value.hasOwnProperty('operation')) {
nestedObj[key] = value.operation
? eval(secondObj[value.mapped_field] + value.operation)
: secondObj[value.mapped_field];
} else {
nestedObj[key] = {};
procedure(value, parentObj, nestedObj[key]);
}
}
return (parentObj = { ...nestedObj });
};
const result = procedure(firstObj);
console.log(JSON.stringify(result));
// {"source_name":"Dollar","amount_money":{"amount":10,"currency":"USD"},"source_id":"123ASD","nested":{"nested":{"nested":{"nested":"Hello"}}}}
旧答案
我不知道在您的firstObj 中嵌套了多少。但是下面的这段代码可以解决你给出的例子。
我通过匹配值将第二个对象的值替换为第一个对象的值。
如果operation 不等于null,使用eval()函数计算以字符串表示的 JavaScript 代码。
const result = {};
for (const [parentKey, parentValue] of Object.entries(firstObj)) {
result[parentKey] = {};
for (const [childKey, childValue] of Object.entries(parentValue)) {
result[parentKey][childKey] = childValue.operation
? eval(secondObj[childValue.mapped_field] + childValue.operation)
: secondObj[childValue.mapped_field];
}
}
console.log(result); //{ amount_money: { amount: 10, currency: 'USD' } }
注意:如果 firstObj 只有一个键,例如 amount_money,您可以只使用一个循环来使您的代码精确。
关于javascript - 通过键查找获取值并替换为嵌套 json 对象中的第二个 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67735229/