简体   繁体   中英

add multiple key/value pairs to object from array javascript

function arrayToList (arr){
    var dataStructure = null;
    for (var i = 0;i < arr.length; i++){
    dataStructure= {value: arr[i]};
    }
    return dataStructure;
}
arrayToList([1,2,3]);

I would simply like this function to create an object that like this:

dataStructure {
    value: 1;
    value: 2;
    value: 3;
}

So far my code keeps updating a singular value. I'm pretty sure I cannot have "value" (same name) multiple times, however, I failed at trying to change it to value, value1, value2, etc. as well

Thank you in advance, sorry newbie question

You can define object before for loop, use bracket notation to set property of object. You can also pass a second parameter to specify the the value to be concatenated to object properties.

 function arrayToList (arr, counter) { var dataStructure = {}; for (var i = 0;i < arr.length; i++, counter++){ dataStructure["value" + counter] = arr[i]; } return dataStructure; } var res1 = arrayToList([1, 2, 3], 1); var res2 = arrayToList([4, 5, 6], 4); console.log(res1, res2);

 function arrayToList (arr){ var dataStructure = {}; // data structure is initialized to an empty object for (var i = 0; i < arr.length; i++) { var key = "value" + i; // generate the key (or var key = "value" + (i + 1); if you want to start with value1, value2 ...) dataStructure[key] = arr[i]; // set the value of the key 'key' to arr[i] } return dataStructure; } var obj = arrayToList([1,2,3]); console.log(obj);

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