[英]How to get name and values from a javascript object into a new list?
I have this JavaScript object which is a collection of multiple lists(I believe).我有这个 JavaScript object 这是多个列表的集合(我相信)。 I need to create a select dropdown with the name being the name of the list, and a number of boxes with background color as per that name.我需要创建一个 select 下拉列表,名称是列表的名称,以及许多具有该名称背景颜色的框。 Like this:像这样:
I am able to parse that object to get all the names of the colors, but I can't find a way to parse the names and the list of values it holds.我能够解析 object 以获取 colors 的所有名称,但我找不到解析名称和它所包含的值列表的方法。 This is how I tried:这就是我尝试的方式:
var
YlGn3 = ['#f7fcb9', '#addd8e', '#31a354'],
YlGn4 = ['#ffffcc', '#c2e699', '#78c679', '#238443'],
YlGn5 = ['#ffffcc', '#c2e699', '#78c679', '#31a354', '#006837'];
var brewer = Object.freeze({
YlGn3: YlGn3,
YlGn4: YlGn4
});
var office = Object.freeze({
YlGn5: YlGn5
});
var colorschemes = {
brewer: brewer,
office: office
};
var scheme_list = [];
for (i in colorschemes){
for(j in colorschemes[i]){
console.log(j);
scheme_list.push(j);
}
}
I was thinking of creating a new object and append every color, along with the list of colors, so I can parse it again to create an option element with it.我正在考虑创建一个新的 object 和 append 每种颜色,以及 colors 的列表,所以我可以再次解析它以创建一个选项元素。 But, I am not able to figure out the best way to do that.但是,我无法找出最好的方法来做到这一点。 Is this the correct approach?这是正确的方法吗?
You use Object.values
along with forEach
multiple times.您多次使用Object.values
和forEach
。
Object.values(colorschemes).forEach(obj=>Object.entries(obj).forEach(([name,colors])=>{
const arr = [];
colors.forEach(color=>arr.push(color));
scheme_list.push([name, arr]);
}));
var YlGn3 = ['#f7fcb9', '#addd8e', '#31a354'], YlGn4 = ['#ffffcc', '#c2e699', '#78c679', '#238443'], YlGn5 = ['#ffffcc', '#c2e699', '#78c679', '#31a354', '#006837']; var brewer = Object.freeze({ YlGn3: YlGn3, YlGn4: YlGn4 }); var office = Object.freeze({ YlGn5: YlGn5 }); var colorschemes = { brewer: brewer, office: office }; var scheme_list = []; Object.values(colorschemes).forEach(obj=>Object.entries(obj).forEach(([name,colors])=>{ const arr = []; colors.forEach(color=>arr.push(color)); scheme_list.push([name, arr]); })); console.log(scheme_list);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.