Home > Software engineering >  How to call json API specific keys
How to call json API specific keys

Time:06-17

can someone help me? i have json like this

[ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
]

But i want to change it like this

[2, 9, 6] and [4, 18, 12]

CodePudding user response:

You can use map function.

var data = [ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
];

const positiveList = data.map(({positive})=> positive);

const negativeList = data.map(({negative})=> negative);

console.log(positiveList);
console.log(negativeList);

Or you can merge into 1 map function.

   var data = [ 
     { "positive": 2, "negative": 4 }, 
     { "positive": 9, "negative": 18 }, 
     { "positive": 6, "negative": 12 } 
    ];

    const [positiveList, negativeList] = data.reduce(([a,b], {positive,negative})=>{ 
      a.push(positive); 
      b.push(negative); 
      return [a,b]; 
    }, [[],[]]);


    console.log(positiveList);
    console.log(negativeList);

CodePudding user response:

This way - tried and tested

let data=[ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
];

let new_d=[]

data.map((e,i,a)=>{Object.keys(e).map((e1,i1,a1)=>{new_d[e1]=[...new_d[e1]||[],e[e1]]})})

console.log(new_d)

enter image description here

CodePudding user response:

You can do it with a simple forEach loop. Like that:

const d = [ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
]

const p = []
const n = []


d.forEach(e => {
  p.push(e.positive)
  n.push(e.negative)
})

console.log(" ", p)
console.log("-", n)

  • Related