按javascript中的键过滤

时间:2019-05-27 04:50:52

标签: javascript jquery arrays object

我想按javascript键进行过滤。

我有一个ajax函数,在传递id时,将obj1一次接一个地成功执行。 我想将所有结果通过key合并并推送到单个对象。 如何在javascript中执行以下操作。

var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}


//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

预期输出:

var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}

3 个答案:

答案 0 :(得分:0)

尝试一下:

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;
}

答案 1 :(得分:0)

尝试做这样的事情。我认为您的钥匙是固定的。点击link进行演示。

  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));
  }

答案 2 :(得分:0)

您可以尝试以下操作,如果结果已经具有值,则将合并值

//
 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
   }]
}
*/