Home > Software design >  How to take a json as input and produce 2 arrays in Javascript?
How to take a json as input and produce 2 arrays in Javascript?

Time:12-14

I want to take a JSON as input and produce 2 arrays, one contains only keys and the other contains only value. But if a key and value are numerically equal then that pair won't take place in these arrays. How can I solve that?

CodePudding user response:

You can iterate over key,values of an object by using Object.entries and then check if key and value are diffrent, put them in the related array. like this:

let obj = {a:5, b:6, c:3, '1':4,'2':2};
let keys = [] , values = [];
Object.entries(obj).forEach(([key,value])=> {
    if(key != value){
        keys.push(key);
        values.push(value)
    }
});

console.log('keys:',keys);
console.log('values:', values);

CodePudding user response:

If I understand, what you want to say, than your assumption doesn't sound right, with this two builtin functions it works and nothing is lost, keys and data are seperated, with builtin functions, no looping needed.

  • Object.values returns all values of an object (mdn docs)
  • Object.keys returns all keys of an object (mdn docs)

It works with Objects and Arrays:

var data = {a:1, b:2, c:3, '1':5,'2':'a'};
// just to visualisze the input data
console.info('data-object:', JSON.stringify(data));
// extracted keys
console.info('keys:',  Object.keys(data));
// extracted values
console.info('values:',  Object.values(data));

var list = [1,2,3,4];
// just to visualisze the input data
console.info('data-list:', JSON.stringify(list));
// extracted keys
console.info('keys:',  Object.keys(list));
// extracted values
console.info('values:',  Object.values(list));

var data2 = {"1":1, "2":2};
// just to visualisze the input data
console.info('data-list:', JSON.stringify(data2));
// extracted keys
console.info('keys:',  Object.keys(data2));
// extracted values
console.info('values:',  Object.values(data2));

  • Related