-1

What is the best way to convert this

const items = [
  { name: "Leon", url: "../poeple" },
  { name: "Bmw", url: "../car" }
];

into this using javascript :

const result = {
  Leon: "../poeple",
  Bmw: "../car"
};
Tedajo Philippe
  • 400
  • 5
  • 20

5 Answers5

2

You could map the objects as entries and get an object from it.

const
    items = [{ name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" }],
    result = Object.fromEntries(items.map(({ name, url }) => [name, url]));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You could just reduce the array:

const items = [{
    name: "Leon",
    url: "../people"
  },
  {
    name: "Bmw",
    url: "../car"
  }
];

const o = items.reduce((o, el) => {
  o[el.name] = el.url;
  return o;
}, {});

console.log(o)

The Array.prototype.reduce method is very flexible, and might be used to reduce an array to another entity:

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Cesare Polonara
  • 3,473
  • 1
  • 9
  • 19
2

There are lots of different approaches as your can see. But if you're new to JavaScript maybe a simple loop over the array to create new keys and values in a new object would be easier to understand.

const items=[{name:"Leon",url:"../poeple"},{name:"Bmw",url:"../car"}];

const out = {};

for (const obj of items) {
  out[obj.name] = obj.url;
}

console.log(out);
Andy
  • 61,948
  • 13
  • 68
  • 95
1

Another way (tested on your example):

function convertit (src) {
  var dest = {}, i;
  for (i = 0; i < src.length; i++) {
    var record = src[i];
    dest[record.name] = record.url;
  }
  return dest;
}
Manna5
  • 39
  • 2
0

Try Like This

const items = [
   { name: "Leon", url: "../poeple" },
   { name: "Bmw", url: "../car" }
];

const newObj = Object.fromEntries(items.map(ele => [ele.name,ele.url]));
console.log(newObj);

Or You can create function like this

const items = [
    { name: "Leon", url: "../poeple" },
    { name: "Bmw", url: "../car" }
  ];


const convertArrayToObject = (array, key) => {
const initialValue = {};
   return array.reduce((obj, item) => {
    return {
      ...obj,
      [item[key]]: item.url,
    };
  }, initialValue);
};

console.log(convertArrayToObject(items, "name"));