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
4 Answers
Reset to default 6You 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条)