简体   繁体   English

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

[英]Assign object value as array in javascript

How to assign the value to array in object value? 如何在对象值中将值分配给数组? It may has multiple input coming in and expected the input appended to array. 它可能有多个输入进来,并期望将输入追加到数组中。

Code: 码:

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

Input: 输入:

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

Expected: 预期:

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

Create a function and an object variable. 创建一个函数和一个对象变量。 Check if the key exist in that object. 检查密钥是否存在于该对象中。 If it does not exist they create the key and push the values 如果不存在,则创建密钥并推送值

 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) 

Hope this helps, 希望这可以帮助,

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

The problem is v empties on each iteration, because of this line: 问题是v清空,因为这条线的每个迭代,:

var v = [];

Try doing this instead: 尝试这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM