Push all values from object to array?
12,596
Solution 1
Without loop:
const input = {two: 2, four: 4, three: 3, twelve: 12};
const myArr = Object.values(input);
console.log(myArr);
// output: [2, 4, 3, 12]
Solution 2
If you writing it in javascript native, use the push() function:
for example:
var persons = {roy: 30, rory:40, max:50};
var array = [];
// push all person values into array
for (var element in persons) {
array.push(persons[element]);
}
good luck
Solution 3
input = {two: 2, four: 4, three: 3, twelve: 12}
const output = Object.keys(input).map(i => input[i])
[2, 4, 3, 12]
This will help you to find exact output.
This link will provide you more information https://medium.com/chrisburgin/javascript-converting-an-object-to-an-array-94b030a1604c
Comments
-
Rory Perro almost 2 years
I'm just starting as a programmer. Can someone help me with this problem? All I have so far is:
var myArr = []; for (var k in input) { myArr.push(
Am I on the right track?
Write a loop that pushes all the values in an object to an array.
input: {two: 2, four: 4, three: 3, twelve: 12} output: [2, 4, 3, 12]