简体   繁体   中英

Manipulating json using javascript

I'm a beginner in javascript and trying to convert json object to list. Any logic would help me.

Converting this:

let obj = { "first_key": [  1, 2, 3, 4 ]
          , "second_key":[ 11,22,33,44 ]
}

to this:

  [ { "first_key": 1, "second_key": 11 } 
  , { "first_key": 2, "second_key": 22 } 
  , { "first_key": 3, "second_key": 33 } 
  , { "first_key": 4, "second_key": 44 } 
  ] 

What I have tried:

 let obj = { "first_key": [1, 2, 3, 4], "second_key": [11, 22, 33, 44] } let new_obj = {}; let list = []; Object.keys(obj).forEach((key) => { new_obj[key] = {}; list.push(obj); }); console.log(list);

with a little practice it becomes almost automatic ...

 let obj = { "first_key": [ 1, 2, 3, 4 ] , "second_key": [ 11, 22, 33 ,44 ] } convert = Object .keys(obj) .reduce((acc, eKey)=>{ obj[eKey].forEach((elm,i)=>{ if (!acc[i]) acc[i] = {} acc[i][eKey] = obj[eKey][i] }) return acc },[]) //proof: convert.forEach((elm, i)=>console.log(`convert[${i}] =`, JSON.stringify(elm)))
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Since you've stated you're a beginner, here is a less complex solution that should hopefully be easier to understand. I've added comments for clarification as well.

 let obj = { "first_key": [1, 2, 3, 4], "second_key": [11, 22, 33, 44] } let keys = Object.keys(obj); let new_arr = []; //we need as many objects in the new_arr as there are values in the obj.first_key array for(let i = 0; i < obj[keys[0]].length; i++) { //there is one new object for each element in the array let new_obj = {}; //for each key in the object, set the value on new_obj //to the value at the corresponding index 'i' keys.forEach(key => { new_obj[key] = obj[key][i]; }); new_arr.push(new_obj); } console.log(new_arr);

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