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
Add a ment  | 

3 Answers 3

Reset to default 3

You 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