Simply
const obj = {};
for (const key of yourArray) {
obj[key] = whatever;
}
or if you prefer "functional" style:
const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {});
using the modern object spread operator:
const obj = yourArray.reduce((o, key) => ({ ...o, [key]: whatever}), {})
Example:
console.log(
[
{ id: 10, color: "red" },
{ id: 20, color: "blue" },
{ id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})
);
Here is how it works:
reduce is initialized with an empty object (empty {} at the end), therefore first iteration variables are acc = {} cur = { id: 10, color: "red" }. Function returns an object - this is why function body is wrapped in parentheses => ({ ... }). Spread operator doesn't do anything on the first iteration, so red: 10 is set as first item.
On the second iteration variables are acc = { red: 10 } cur = { id: 20, color: "blue" }. Here the spread operator expands acc and the function returns { red: 10, blue: 20 }.
Third iteration acc = { red: 10, blue: 20 } cur = { id: 30, color: "green" }, so when acc is spread inside the object, our function returns the final value.
Simply
const obj = {};
for (const key of yourArray) {
obj[key] = whatever;
}
or if you prefer "functional" style:
const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {});
using the modern object spread operator:
const obj = yourArray.reduce((o, key) => ({ ...o, [key]: whatever}), {})
Example:
console.log(
[
{ id: 10, color: "red" },
{ id: 20, color: "blue" },
{ id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})
);
Here is how it works:
reduce is initialized with an empty object (empty {} at the end), therefore first iteration variables are acc = {} cur = { id: 10, color: "red" }. Function returns an object - this is why function body is wrapped in parentheses => ({ ... }). Spread operator doesn't do anything on the first iteration, so red: 10 is set as first item.
On the second iteration variables are acc = { red: 10 } cur = { id: 20, color: "blue" }. Here the spread operator expands acc and the function returns { red: 10, blue: 20 }.
Third iteration acc = { red: 10, blue: 20 } cur = { id: 30, color: "green" }, so when acc is spread inside the object, our function returns the final value.
The new Object.fromEntries, from ECMAScript 2019, makes it even easier to transform values from an array into keys in an object like follows
const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
dynamicArray.map(year => [year, {
something: "based",
on: year
}])
)
console.log(obj)
Or maybe to solve your own original problem
const width = 1920
const height = 1080
const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
dynamicArray.map((year, i) => [year, {
x: (( i + 1) / 5) * width,
y: height / 2
}])
)
console.log(obj)
javascript - Creating an array from object properties with Object.keys() vs Object.values() - Stack Overflow
How might I extract the property values of a JavaScript object into an array? - Stack Overflow
How to convert an Object {} to an Array [] of key-value pairs in JavaScript - Stack Overflow
javascript - How to obtain the object values from an array with one object and create a new array with just the object values - Stack Overflow
Here is a shorter way of achieving it:
let result = objArray.map(a => a.foo);
OR
let result = objArray.map(({ foo }) => foo)
You can also check Array.prototype.map().
Yes, but it relies on an ES5 feature of JavaScript. This means it will not work in IE8 or older.
var result = objArray.map(function(a) {return a.foo;});
On ES6 compatible JS interpreters you can use an arrow function for brevity:
var result = objArray.map(a => a.foo);
Array.prototype.map documentation
Use .keys() if you need to do something with the keys other than to retrieve the values. Otherwise, you're only getting the keys in order to access the values, which is redundant if you can get the values directly using a different method - so, in that case, might as well use Object.values() from the beginning.
An example of where Object.keys could be useful:
const obj = {
prop1: 'val1',
prop2: 'val2'
};
const result = Object.keys(obj).map((key) => [key, obj[key]]);
console.log(result);
You may also use Object.entries to get both the key and value at once:
const obj = {
prop1: 'val1',
prop2: 'val2'
};
const result = Object.entries(obj).map(([key, val]) => key + '---' + val);
console.log(result);
Array.from(arrayLike [, mapFn [, thisArg]]) is also another method to create an array from an array-like or iterable object and is really simple. Second argument is a map function to call on every element of the array
const cats = {
abyssinian: {
number: 23
},
persian: {
number: 12
},
siamese: {
number: 7
}
};
const catsArray = Array.from(Object.values(cats), breed => breed.number)
console.log(catsArray);
You can use Object.keys() and map() to do this
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [key, obj[key]]);
console.log(result);
The best way is to do:
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.entries(obj);
console.log(result);
Calling entries, as shown here, will return [key, value] pairs, as the caller requested.
Alternatively, you could call Object.values(obj), which would return only values.
If you know for sure that it will only have one object then all you need to do is:
Object.values(myVar[0])
see docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Note: If you need to support older browsers like internet explorer you will have to use Object.keys paired with map
Try This, You get the result you want.
let newArr = [];
for (var key in myVar[0]) {
if (myVar[0].hasOwnProperty(key)) {
newArr.push(myVar[0][key]);
}
}
console.log('New Array: ',newArr);
Output: [ 'A', 'B', 'C', 'D' ]
Hello
How do I create an array of objects from an array?
My desired outcome is this:
const newArr = [
{ value: 'roman', label: 'Roman' },
{ value: 'thor', label: 'Thor' },
{ value: 'saige', label: ''Saige }
]My starting array is this:
cosnt arr = ['Roman', 'Thor', 'Saige']
I believe I would use .map() but not doing it right. This is what I have:
let arr2 = arr.map(el => ({value: el.toLower(), label: el}))Thanks!