admin管理员组文章数量:1317898
I'd like to convert a list of items into a list of dictionaries. See below for my example.
list_of_items = ['a','b','c','d']
desired_result = [{'name':'a'},{'name':'b'},{'name':'c'},{'name':'d'}]
My attempt:
function myAttempt(list_of_items){
list_of_items.forEach(function (i) {
return {'name':i};
});
return list_of_items
};
myAttempt(list_of_items)
I'd like to convert a list of items into a list of dictionaries. See below for my example.
list_of_items = ['a','b','c','d']
desired_result = [{'name':'a'},{'name':'b'},{'name':'c'},{'name':'d'}]
My attempt:
function myAttempt(list_of_items){
list_of_items.forEach(function (i) {
return {'name':i};
});
return list_of_items
};
myAttempt(list_of_items)
Share
Improve this question
asked Mar 2, 2017 at 18:49
ChrisChris
5,83418 gold badges71 silver badges126 bronze badges
2
- JavaScript doesn't have dictionaries. It has, in your case, arrays and objects, and you're looking to turn your array into an array of objects. – j08691 Commented Mar 2, 2017 at 18:51
-
too easy with
Array.prototype.map()
function – RomanPerekhrest Commented Mar 2, 2017 at 18:52
3 Answers
Reset to default 3You can use map()
method to return array of objects.
var list_of_items = ['a','b','c','d']
var result = list_of_items.map(function(e) {
return {name: e}
})
console.log(result)
Or if you can use ES6 arrow functions you can get same result like this.
var result = list_of_items.map(e => ({name: e}))
One of the ways how to do it. You can pass various arrays into the function, same with the key
. May be name
or whatever you like.
let list_of_items = ['a','b','c','d'],
result = [];
function myAttempt(arr, key){
arr.forEach(function(v){
let obj = {};
obj[key] = v;
result.push(obj);
});
console.log(result);
}
myAttempt(list_of_items, 'name');
I don't think this answer is duplicate with @Kinduser's answer, but it looks shorter:
var list_of_items = ['a','b','c','d'];
list_of_items.forEach(function(element, index, list) {
list[index] = {'name': element};
});
console.log(list_of_items);
本文标签: arraysHow to create list of dictionaries from list of items in javascriptStack Overflow
版权声明:本文标题:arrays - How to create list of dictionaries from list of items in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742034671a2417115.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论