简体   繁体   中英

How do i add a key value pair to an asociative array in javascript

let finaloutput = {};
   $.each( arr, function(index,key) { 
     let outarray = [];
     // var id sourced from another function
     outarray.push(id,index,key);  
     //??finaloutput[id].push(outarray);
                        }

In the above code i am trying to store an object similar to below. Each time the loop grabs the same id it appends the array in the finaloutput object eg id:index:key

1st loop where id = 7 index=param 1 key=val1

                  {"7":[{param1:val1}]}

2nd.. id = 7 index=param 2 key=val2

                  {"7":[{param1:val1,param2:val2}]}

3rd... id = 8 index=param 1 key=val1

                  {"7":[{param1:val1,param2:val2}],"8":[{param1:val1}]}

How do i achieve this

I tried to generated similar output using sample data:

    `let indx = ["param1", "param2", "param3", "param4", "param5"]
    let key = ["k1", "k2", "k3", "k4", "k5"]
    let id = ["1", "2", "3", "4", "5"]
    let resultObj = {}
    for (let i = 0; i < 5; i++) {
      if (resultObj[id]) {
        let temp=Object.assign({}, {[indx[i]]:key[i]}, ...resultObj[id[i]])
        resultObj[id[i]] = [temp];
      }
      else{
        let ob=[{[indx[i]]:key[i]}]
        resultObj[id[i]]=ob
      }
    }
    console.log(resultObj)`

In your case you can do something like: let finaloutput = {}; $.each(arr, function (index, key) { if (finaloutput[id]) { let temp = Object.assign({}, { [index]: key }, ...finaloutput[id]) finaloutput[id] = [temp]; } else { let temp2 = [{ [index]: key }] finaloutput[id] = temp2 } } let finaloutput = {}; $.each(arr, function (index, key) { if (finaloutput[id]) { let temp = Object.assign({}, { [index]: key }, ...finaloutput[id]) finaloutput[id] = [temp]; } else { let temp2 = [{ [index]: key }] finaloutput[id] = temp2 } }

Note Please refer to my example to get better understanding incase I was not able to exactly formulate answer of your code or it gives error

You have an object finaloutput . So your goal can be divided into smaller pieces:

  • just create a key in object
  • assign an array to the above key
  • push desired values into array

So the code should look like this:

let finaloutput = {};
$.each( arr, function(index,key) { 
    finaloutput[key] = []; 
    let outarray = [];
    // var id sourced from another function
    finaloutput[key].push({id:key});  
}     

Or it can be done using reduce() method. Let me show an example::

 const array = ["one", "two", "three", "one", "one", "two", "two", "three", "four", "five"]; const result = array.reduce((a, c) => { a[c]=a[c] || []; a[c].push({yourKey: c}); return a; }, {}) console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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