How to convert an array into a nested plain object

Viewed 165

How would I take an array that console.logs as this:

[Kzljszzz15OFcln1XGM, {make: "John Deere ", model: "5055", uid: "Kzljszzz15OFcln1XGM", year: "1953"}]

and turn it into this plain object? :

{Kzljszzz15OFcln1XGM: {make: "John Deere ", model: "5055", uid: "Kzljszzz15OFcln1XGM", year: "1953"}

where it's a key value pair where the value is more key value pairs?

So far I've tried:

const myArray = //the array mentioned above
function toObject(arr) {
        const rv = {};
        for (let i = 0; i < arr.length; ++i) {
        rv[i] = arr[i];
          return rv;
}

console.log(toObject(myArray));

And also:

Object.assign({}, myArray);

These won't even convert myArray into a plain object, let alone the format I'm after for some reason.

I've set after this problem in a couple of totally wrong directions because I was logging from the wrong places in my code. But now I'm sure I'm asking the right question. Any help would be appreciated!

2 Answers

If you want to take even indexes as keys and odd indexes as values, you can convert an array to an object like this:

function toObject(arr) {
  const rv = {};
  for (let i = 0; i < arr.length; i += 2) {
    rv[arr[i]] = arr[i + 1];
  }
  return rv;
}

Given an array like this:

var arr = ["Kzljszzz15OFcln1XGM", {make: "John Deere ", model: "5055", uid: "Kzljszzz15OFcln1XGM", year: "1953"}];

The above function will give:

{ Kzljszzz15OFcln1XGM:
   { make: 'John Deere ',
     model: '5055',
     uid: 'Kzljszzz15OFcln1XGM',
     year: '1953' } }

var arr = [ "Kzljszzz15OFcln1XGM" , 
 {
  make: "John Deere ", 
  model: "5055", 
  uid: "Kzljszzz15OFcln1XGM",
  year: "1953"
 }
];

for(var prop in arr) {

 var cheackObjProp = (arr[prop] === "Kzljszzz15OFcln1XGM") ? true : false;
 var obj = {};

 //-------first index of arr----------
 if(cheackObjProp) {

 var objprop = arr[prop];

 //------second index of arr-----------
 }else {
  
  obj[objprop] = arr[prop];
 }

};

console.log(obj);

Related