Home > Software design >  a method that returns an object composed of key-value pairs
a method that returns an object composed of key-value pairs

Time:08-22

Task description: Write a method that returns an object composed of key-value pairs. Expected Result: [['a', 1], ['b', 2]] => { a: 1, b: 2 } Task Complexity: 2 of 5 @param {Array} array - a deep array of pairs @returns {Array}. i came up with the solution but return { [key]: value } is not happening.

const fromPairs = (array) => {
  array.forEach((element) => {
    if (Array.isArray(element)) {
      const [key, value] = element;
      return { [key]: value };
    }
  });
};
const data3 = [
  ["a", 1],
  ["b", 2],
];
console.log(fromPairs(data3)); // { 'a': 1, 'b': 2 }

CodePudding user response:

There is a built-in method Object.fromEntries:

const data3 = [
  ["a", 1],
  ["b", 2],
];

const object = Object.fromEntries(data3);

But if the point is to do it manually, I'd go with Array.prototype.reduce:

const object = data3.reduce(
    (carry, [key, value]) => ({
        ...carry,
        [key]: value,
    }),
    {}
);

CodePudding user response:

You can simplify this by iterating through only the outer array, and creating the object by the expected index numbers of the inner one. Then return the object after the forEach loop is done:

const data3 = [['a', 1],['b', 2]]

function fromPairs(arr) {
  const obj = {}
  arr.forEach(el => {
    if(Array.isArray(el)) {
      obj[el[0]] = el[1]
    }
  })
  return obj
}

console.log(fromPairs(data3))

  • Related