Convert JSON to Array

Asked

Viewed 132 times

0

I have the following JSON:

let result = {"0":4,"10":4,"30":6,"60":9,"90":12,"120":15,"150":18,"180":21}

I need to convert to Array in the following format:

[{"0":4},{"10":4},{"30":6},{"60":9},{"90":12},{"120":15},{"150":18},{"180":21}]

I’m trying like this without success:

let dados = JSON.parse(result)

2 answers

3


let result = {"0":4,"10":4,"30":6,"60":9,"90":12,"120":15,"150":18,"180":21};

const transformation = Object.entries(result).map(([key, value]) => ({ [key]: value }));

console.log(transformation);


Array.prototype.map()

The map() method invokes the callback function passed by argument to each Array element and returns a new Array as a result.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots é [1, 2, 3], numbers ainda é [1, 4, 9]

1

If I understand correctly, you need to iterate through the keys and values of the original object by separating objects from each one:

Object.keys(result).map((key) => 
{
    let objToReturn = {};
    objToReturn[key] = result[key];
    return objToReturn;
});

In the code above, a map is done in an array from each key of the initial object, creating a new object, assigning a new property with the current value of the key of the initial object and returning the new.

The result would be:

0: {0: 4}
1: {10: 4}
2: {30: 6}
3: {60: 9}
4: {90: 12}
5: {120: 15}
6: {150: 18}
7: {180: 21}

I hope I’ve helped in some way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.