How to take a json as input and produce 2 arrays in Javascript?

Viewed 170

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?

2 Answers

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);

If I understand, what you are asking, there are two builtin functions, that give you the keys and data are seperated, 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