Home > database >  Convert JSON data column to specific array
Convert JSON data column to specific array

Time:01-20

I want to convert my json to array

var data = {1:{id: '2014-924', name: 'abc'},2:{id: '2014-925', name: 'xyz'}};

var result = ['2014-924','2014-925'];`outout`

CodePudding user response:

The value you want in your result array is present in the values for id in your object. You can loop through the values of the object to get the 'id'.

Use Object.values() to get an array of values of your object. Then loop through the array to collect the id.

Here is an example using Array.map

var data = {1:{id: '2014-924', name: 'abc'},2:{id: '2014-925', name: 'xyz'}};


const result = Object.values(data).map(x => x.id)

console.log(result)

CodePudding user response:

Your data should be in the following format

var data = '{"data": [{"id": "2014-924", "name": "abc"}, {"id": "2014-924", "name": "abc"}]}'

The you can deserialise the json using JSON.parse();

var resultObject = JSON.parse(data);

And to create the result array:

var result = [resultObject.data[0].id, resultObject.data[1]];
  • Related