Try with Array.reduce():
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from prasanth on Stack OverflowTry with Array.reduce():
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
javascript - How to convert an array into an object? - Stack Overflow
How to convert array to object with a constant key "id" .
Convert array to object in React JS
Converting an array to a JSON object with custom key names
ECMAScript 6 introduces the easily polyfillable Object.assign:
The
Object.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length property of the array is not copied because it isn't enumerable.
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
For custom keys you can use reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
With a function like this:
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
Your array already is more-or-less just an object, but arrays do have some "interesting" and special behavior with respect to integer-named properties. The above will give you a plain object.
edit oh also you might want to account for "holes" in the array:
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
if (arr[i] !== undefined) rv[i] = arr[i];
return rv;
}
In modern JavaScript runtimes, you can use the .reduce() method:
var obj = arr.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
That one also avoids "holes" in the array, because that's how .reduce() works.
I have the following array
OriginalArray = [100,200,300]
WantedObject = [{id:100},{id:200},{id:300}]
I tried it with reduce but it changes the id. Any help is appreciated 🙏