在JavaScript中将对象值分配为数组

时间:2019-01-23 08:16:59

标签: javascript jquery arrays loops object

如何在对象值中将值分配给数组?它可能有多个输入进来,并期望将输入追加到数组中。

代码:

var ob = {};
$.each( input, function( key, value ) {
    var v = [];
    ob[key] = v.push(value);
      console.log( v );     
      console.log( "obj: " + ob );                          
      console.log( key + ": " + value );
    });

输入:

First input- {A: "34",B: "2"}
Second input- {A: "21",B: "11"}

预期:

ob = {A: ["34","21"] ,B: ["2","11"]}

3 个答案:

答案 0 :(得分:1)

创建一个函数和一个对象变量。检查密钥是否存在于该对象中。如果不存在,则创建密钥并推送值

let input1 = {
  A: "34",
  B: "2"
}
let input2 = {
  A: "21",
  B: "11"
}

// a object which will hold the key and value

let finalObj = {};
// create a function which will be called o add key an value property to object
function createObj(obj) {
  // iterate the object
  for (let keys in obj) {
    // check if final object has the relevent key
    if (finalObj.hasOwnProperty(keys)) {
      // if it has that key then push the value according to the key
      finalObj[keys].push(obj[keys])
    } else {
      finalObj[keys] = [obj[keys]]
    }
  }

}

createObj(input1)
createObj(input2)
console.log(finalObj)

答案 1 :(得分:1)

希望这会有所帮助,

var ob = {};

$.each(input, function(key, value) {
    if (!ob[key]) {
        ob[key] = [];  // Creates a new Array for the key, if no array is there
    }
    ob[key].push(value);  // Pushes the value to the array of the particular key
});

答案 2 :(得分:1)

问题在于,由于以下这一行,每次迭代v为空:

var v = [];

尝试执行以下操作:

$.each(input, (key, val) => {
    if (ob[key]) {
        ob[key].push(val);
    } else {
        ob[key] = [val];
    }
});