Home > Back-end >  Convert object containing objects to array containing objects
Convert object containing objects to array containing objects

Time:04-01

I have a JSON object that will sometimes be an object (a single instance) and sometimes be an array (multiple instances of the object). I need to write an if statement that basically says if this section of JSON is an object, wrap it in an array containing that single object, and if it's an array containing multiple objects, return that array. In either instance I'm returning an array containing either 1 or multiple objects. Here is what the JSON looks like when it is NOT an array.

"link": {
  "values": {
    "key1": "value1",
    ...
    "key8": "value8"
    },
  "key9": "value9"
  }

And it should look like this when it's an array:

"link": [{
  "values": {
    "key1": "value1",
    ...
    "key8": "value8",

    },
  "key9": "value9"
  }]

CodePudding user response:

You can use Array.isArray to check, then convert

let data = {
  "link": {
    "values": {
      "key1": "value1",
      "key8": "value8"
    },
    "key9": "value9"
  }
}

data.link = Array.isArray(data.link) ? data.link : [data.link];
console.log(data)

CodePudding user response:

This can be done by writing a simple function that checks if it's an array.

const returnArray = (value) => {
  if (Array.isArray(value) {
    return value;
  }
  return 
}

CodePudding user response:

updated the answer of @Kinglish to typescript one because you cannot change types of defined value as it giving error for this either simply ignore the typescript or define types that simply accept link in object and array of object or just created new variable that expect a link in the array and wrap it inside data by simply doing this:

const data = {
  link: {
    values: {
      key1: 'value1',
      key8: 'value8',
    },
    key9: 'value9',
  },
};

// This is the type of data you can't change it by default and it doesn't expect array of object of `link`.
// const data: {
//   link: {
//     values: {
//       key1: string;
//       key8: string;
//     };
//     key9: string;
//   };
// };

const linkArray = { link: Array.isArray(data.link) ? data.link : [data.link] };

// Now this is the type of linkArray that expect array of object of `link`
// const linkArray: {
//   link: {
//     values: {
//       key1: string;
//       key8: string;
//     };
//     key9: string;
//   }[];
// };


console.log('data', data);
console.log('linkArray', linkArray);
  • Related