0

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"]}
1
  • 5
    var v = []; empties v on each iteration step. Commented Jan 23, 2019 at 8:19

3 Answers 3

2

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
});
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

The problem is v empties on each iteration, because of this line:

var v = [];

Try doing this instead:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.