Leonardo Silva
Leonardo Silva

Reputation: 79

Transform nested array of objects to an object

I am trying to convert a nested array to an object, I made several attempts but without success.

these are the data i have

[
  ['key1', { childKey1: "text" }, { childKey2: "text" }],
  ['key2', { childKey1: "text" }, { childKey2: "text" }]
]

this is the data i need

{
  key1: {
    childKey1: "text",
    childKey2: "text"
  },
  key2: {
    childKey1: "text",
    childKey2: "text"
  }
}

Upvotes: 2

Views: 541

Answers (4)

Michalis Garganourakis
Michalis Garganourakis

Reputation: 2930

.reduce() method is another way to approach this.

const arr = [['key1', {childKey1: "text"}, {childKey2: "text"}], ['key2', {childKey1: "text"}, {childKey2: "text"}]];

const newArr = arr.reduce((accumulator, currVal) => {
  const [key, ...values] = currVal; // destruct array and separate key from all other values
  
  accumulator[key] = Object.assign({}, ...values); // assign values to your final object, using the key extracted above
  
  return accumulator;
}, {});

console.log(newArr);

Upvotes: 1

Nicholas Siegmundt
Nicholas Siegmundt

Reputation: 869

I know this was already answered, but here's my attempt at it:

let jsonArray = [['key1', {childKey1: "text"}, {childKey2: "text"}], ['key2', {childKey1: "text"}, {childKey2: "text"}]];
let newJson  = {};

for(var i=0; i<jsonArray.length; i++){
	newJson[jsonArray[i][0]] = Object.assign({}, ...jsonArray[i].slice(1));
}

console.log(newJson);

Upvotes: 0

racsoraul
racsoraul

Reputation: 196

You may try reduce to achieve such task. You could do something like this:

    const data = [
      ["key1", { childKey1: "text" }, { childKey2: "text" }],
      ["key2", { childKey1: "text" }, { childKey2: "text" }]
    ];
    
    function dataToJSON(data) {
      return data.reduce((acc, current) => {
        const [key, ...values] = current;
        acc[key] = Object.assign({}, ...values);
        return acc;
      }, {});
    }

    console.log(dataToJSON(data));

Works perfect for any number of children. You have to be careful with repeated keys not to overwrite a previous one.

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 192867

Map the data to entries - [[key, value], [key, value]]. Use destructuring to get the key (the 1st item in a sub-array), and rest syntax to get an array of objects. Merge the array of objects by spreading the array of objects into Object.assign() to get the value. Use Object.fromEntries() to convert the entries to an object.

const data = [['key1', {childKey1: "text"}, {childKey2: "text"}], ['key2', {childKey1: "text"}, {childKey2: "text"}]]

const result = Object.fromEntries(data.map(
  ([k, ...v]) => [k, Object.assign({}, ...v)]
))

console.log(result)

Upvotes: 3

Related Questions