Goutam
Goutam

Reputation: 1367

Converting object to array within an object in JavaScript

I am getting back data in a format that is not acceptable to the processing system and I am trying to convert the data. Below is the data I get and the required JSON below that. I tried different things like finding an Object within the data and checking if it has more than one element then converting that object to Array[] but I am unable to do so.

If you have any inputs, I would appreciate it.

if(typeof ob1=== "object" && Object.keys(ob1.length > 1) && typeof Object.keys(ob1) === "object" )
{
    console.log(ob1); // I get all the objects and not the parent object i need to change. 
}

Present data:

ob1 : {id: 1, details: Object, profession: "Business"}

JSON:

{
  "id": "1",
  "details": {
    "0": {
      "name": "Peter",
      "address": "Arizona",
      "phone": 9900998899
    },
    "1": {
      "name": "Jam",
      "address": "Kentucky",
      "phone": 56034033343
    }
  },
  "profession": "Business"
}

Required data:

{id: 1, details: Array[2], profession: "Business"}

Required JSON:

{
  "id": "1",
  "details": [
    {
      "name": "Peter",
      "address": "Arizona",
      "phone": 9900998899
    },
    {
      "name": "Jam",
      "address": "Kentucky",
      "phone": 56034033343
    }
  ],
  "profession": "Business"
}

Upvotes: 0

Views: 46

Answers (1)

yBrodsky
yBrodsky

Reputation: 5041

You have to go through the details object and convert it into an array:

var x = {
  details: {

    0: {a: 1},
    1: {a: 2}
  }
}

var detailsArr = [];

for(key in x.details) {
  detailsArr.push(x.details[key]);
}

x.details = detailsArr;

//x.details = [{a: 1}, {a: 2}]

Upvotes: 2

Related Questions