javascript - JS: Converting dictionary to a list of dictionaries - Stack Overflow

I have a dictionary and I want to map it so that it bees a list of dictionaries. How would I do that in

I have a dictionary and I want to map it so that it bees a list of dictionaries. How would I do that in js?

var dict = {
"key1" : 100,
"key2" : 200,
"key3" : 300
}
var data = [
{"key1" : 100},
{"key2" : 200},
{"key3" : 300}
]

I have a dictionary and I want to map it so that it bees a list of dictionaries. How would I do that in js?

var dict = {
"key1" : 100,
"key2" : 200,
"key3" : 300
}
var data = [
{"key1" : 100},
{"key2" : 200},
{"key3" : 300}
]
Share Improve this question asked Jul 12, 2020 at 21:48 AA24AA24 471 silver badge6 bronze badges 1
  • Why would you do that? It's harder to work with the resulting data structure. What are you trying to do? – Thomas Commented Jul 12, 2020 at 22:10
Add a ment  | 

4 Answers 4

Reset to default 6

You can use Object.entries() to convert the object to an array of key-value pairs. You can then .map() this array to an array of objects.

var dict = {
  "key1" : 100,
  "key2" : 200,
  "key3" : 300
}

var data = Object.entries(dict).map(([key, value]) => ({[key]: value}))

console.log(data)

you could use Object.entries and map to make key value objects

var dict = {
  "key1" : 100,
  "key2" : 200,
  "key3" : 300
  }

  const re=Object.entries(dict).map(o=>({[o[0]]:o[1]}))
  console.log(re)

You can use Object.keys() and Array.map() to get the result:

var dict = {
"key1" : 100,
"key2" : 200,
"key3" : 300
}

let result = Object.keys(dict).map(k => ({[k]: dict[k]}));
console.log(result);

You can simply declare a variable to store list and loop through dict. On each iteration make a dict from key value and push in list.

var dict = {
  "key1": 100,
  "key2": 200,
  "key3": 300
}
var data = [];
for (key in dict) {
  var subDict = {}
  subDict[key] = dict[key]
  data.push(subDict)
}
console.log(data)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744206313a4563120.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信