简体   繁体   中英

Transfer data from a Javascript object to an array. What's wrong with my array?

We need to transfer the data from the javascript object to the left into an array . Initialize a new array called userDataArray and add all of the data from the object into the array by calling it from the object using the number keys that have been added to the object .

When you are done, you should have the same data from the object that has already been written, but in an array , without having to retype each of the variables separately.

var userData = {
  1: true,
  2: true,
  3: "00QRA10",
  4: "slimer42",
  5: "FFASN9111871-USN16"
};

var userDataArray = [0,1,2,3,4];

You can use new function like Object.values to get values from object, and Object.keys to get keys from the object.

var userData = {
  1: true,
  2: true,
  3: "00QRA10",
  4: "slimer42",
  5: "FFASN9111871-USN16"
};

var userDataArray = Object.values(userData)

Not sure if this is what you want but...

 var userData = { 1: true, 2: true, 3: "00QRA10", 4: "slimer42", 5: "FFASN9111871-USN16" }; var outputArray = []; for (var i = 0; i < Object.keys(userData).length; i++) { outputArray.push(userData[Object.keys(userData)[i]]); } console.log(outputArray); 

taking it apart: Object.keys(userData) is the list (array) of key names. In this case it is 1, 2, 3, 4, and 5. outputArray.push() adds an element to the array. Object.keys(userData)[i] is the name of the object element that we're on, and userData[Object.keys(userData)[i]] is just the element that we're on. So every time we go through the for loop, we add another element to the array.

Your example uses 1, 2, 3, 4, and 5 for their element names though, so something like this might work better:

 var userData = { 1: true, 2: true, 3: "00QRA10", 4: "slimer42", 5: "FFASN9111871-USN16" }; var outputArray = []; for (var i = 0; i < Object.keys(userData).length; i++) { outputArray.push(userData[i+1]); } console.log(outputArray); 

In this example, instead of taking the element name out of the key array we assume that it is a number and that the numbers are in a sequence that starts with 1.

The reason why your solution didn't work

is because you didn't call the numbers from the object. You would've had to use userData.1 , userData.2 , userData.3 , etc.

You can loop through an object and use the keys to get the values.

 var userData = { 1: true, 2: true, 3: "00QRA10", 4: "slimer42", 5: "FFASN9111871-USN16" }; var userDataArray = []; for (var key in userData) { userDataArray.push(userData[key]) } console.log(userDataArray) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM