Home > Software engineering >  JS split object with key value pairs
JS split object with key value pairs

Time:01-26

I' m trying to write a code which is supposed to convert the array of arrays into an array with objects with key: value pairs inside. I got stuck with the following, where everything is fine besides I'm getting the word keys instead of actual keys inside my objects.

var array = [["white", "goodness"], ["green", "grass"]];


var obj={};
for (var i=0; i<array.length;i  ){
  for (var z=0; z < 1; z  ){
obj[array[i][z]] = array[i][z 1];

  }
}


const separateObject = obj => {
  const res = [];
  const keys = Object.keys(obj);
  keys.forEach(key => {
     res.push({
     keys : obj[key]
     });
  });
  return res;
};
console.log(separateObject(obj));

CodePudding user response:

You need to change the key in the res.push statement to be the variable "key" instead of the string "keys".

res.push({
     [key] : obj[key]
     });

CodePudding user response:

You can use simple map like:

const array = [
  ["white", "goodness"],
  ["green", "grass"]
];
const result = array.map(el => {
  return { 
    [el[0]]: el[1]
  };
});

console.log(result);

CodePudding user response:

This works by mapping the array of entries to a new array with the first element of the entry being the key and the second being the value. Destructuring to [key, value] is a bit cleaner and verbose than v[0] and v[1]

const array = [["white", "goodness"], ["green", "grass"]];

const separateObject = arr => {
  return arr.map(([key, value]) => ({ [key]: value }));
};

console.log(separateObject(array));

  • Related