skip to Main Content

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`

2

Answers


  1. 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]];
    
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search