3 回答

TA贡献1829条经验 获得超9个赞
尝试做这样的事情。我假设你的钥匙是固定的。
var output = {};
var id = ["trans", "fund"]
//on first call
var obj1 = {
country: "SG",
trans: [{
rate: 20,
members: 100
}]
}
//on second call
var obj2 = {
country: "TH",
fund: [{
rate: 20,
members: 100
}]
}
function getObj(selectedId) {
console.log(id); // global variable.
if(!id) return;
id.forEach(x => {
let obj1Key = obj1[x];
if (obj1Key) output[x] = obj1Key;
let obj2Key = obj2[x];
if (obj2Key) output[x] = obj2Key;
})
console.log('output object', output);
console.log('JSON:', JSON.stringify(output));
}

TA贡献1801条经验 获得超8个赞
您可以尝试如下,如果结果已经有值,这将合并值
//
var id =["trans", "fund"];
var result = {};
function getObj(obj){
id.map(val => {
if(result[val]) { result[val] = [...result[val], ...obj[val]]}
else result[val] = obj[val]
})
}
//on first call
var obj1={
country: "SG",
trans: [{
rate: 20,
members: 100
}]
}
getObj(obj1)
/*
{
trans: [{
rate: 20,
members: 100
}]
}
*/
//on second call
var obj1={
country: "TH",
fund: [{
rate: 20,
members: 100
}]
}
getObj(obj2)
/*
{
trans: [{
rate: 20,
members: 100
}],
fund: [{
rate: 20,
members: 100
}]
}
*/

TA贡献1807条经验 获得超9个赞
试试这个:
var id =["trans", "fund"];
var result = {};
//on first call
var obj1={
country: "SG",
trans: [{
rate: 20,
members: 100
}]
}
result = getObj(result,obj1);
//on second call
var obj1={
country: "TH",
fund: [{
rate: 20,
members: 100
}]
}
result = getObj(result,obj1);
console.log(result);
function getObj(result,obj){
for (let i = 0; i < id.length; i++) {
if (obj[id[i]]) {
result[id[i]] = obj[id[i]];
return result;
}
}
return result;
}
添加回答
举报