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]
7 Answers 7
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
Comments
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]
Comments
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
var myArr = [];
var input = {two: 2, four: 4, three: 3, twelve: 12};
for (var k in input) {
myArr.push(input[k]);
}
alert(myArr);
Comments
data.input[k] is what you want
var data = {input: {two: 2, four: 4, three: 3, twelve: 12}}, myArr = [];
for(k in data.input) myArr.push(data.input[k]);
Comments
Using underscore.js:
var myArr = _.values(input);
It's a very useful library, and only 5.3k when gzipped
Comments
In each iteration of the for in loop the variable k gets assigned the next property name in the object input, so you have to push input[k]. For the case that the object has properties from its prototype and you only want to push the objects own properties to the array (that is probably what you want to do) you should use hasOwnProperty.
var input: {two: 2, four: 4, three: 3, twelve: 12}
var myArr = [];
for (var k in input) {
// if( input.hasOwnProperty( k) ) { //not necessary
myArr.push( input[k] );
// }
}
Be aware that for in loops over the object in arbitrary order, i.e., the order of the items in the array might not be what you expect it to be.
See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
EDIT: as Alnitak has mentioned in a comment to the OP it is probably not necessary to use hasOwnPropery() nowadays.
1 Comment
.hasOwnProperty is unnecessary. Anyone who extends Object.prototype without doing it the safe ES5 way (via Object.defineProperty) to make the extension non-enumerable deserves all they get.
input[k]to the arrayhasOwnProperty