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"
};
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"
};
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);
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
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);
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;
}
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"));