从对象列表Javascript / TypeScript中获取所有可能的对象键

时间:2016-12-22 16:34:22

标签: javascript arrays list object typescript

我有一个像这样的对象列表:

[ 
  { item1: "1", item2: "2" },
  { item1: "3", item2: "4", item3: "5" },
  { item1: "6" },
  { item1: "7", item2: "8", item3: "9", item4: "10" },
]

我需要能够获得所有可能键的列表:

["item1", "item2", "item3", "item4" ]

我尝试使用Object.Keys,但这需要我指定一个特定的对象,问题是,列表是动态制作的,因此我不知道键和值。

4 个答案:

答案 0 :(得分:2)

您可以Array#reduce方法使用Object.keys方法。



var data = [{
  item1: "1",
  item2: "2"
}, {
  item1: "3",
  item2: "4",
  item3: "5"
}, {
  item1: "6"
}, {
  item1: "7",
  item2: "8",
  item3: "9",
  item4: "10"
}, ];

var res = data.reduce(function(arr, o) {
  return Object.keys(o).reduce(function(a, k) {
    if (a.indexOf(k) == -1) a.push(k);
    return a;
  }, arr)
}, []);

console.log(res);




答案 1 :(得分:1)

var obj=[ 
  { item1: "1", item2: "2" },
  { item1: "3", item2: "4", item3: "5" },
  { item1: "6" },
  { item1: "7", item2: "8", item3: "9", item4: "10" },
],
  keys=[];
  obj.forEach(function(element){
    for (var key in element) {
        if(keys.indexOf(key)===-1){
          keys.push(key);
         }
    }
  });
  console.log(keys);

答案 2 :(得分:1)

您可以使用Set收集密钥。

var obj = [{ item1: "1", item2: "2" }, { item1: "3", item2: "4", item3: "5" }, { item1: "6" }, { item1: "7", item2: "8", item3: "9", item4: "10" }],
    items = obj.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []);

console.log(items);

答案 3 :(得分:1)

如果找到比当前

更长的元素,您应该遍历列表并获取键数组
from bokeh.io import curdoc
from bokeh.layouts import row
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, HoverTool, CustomJS

x = list(range(-20, 21))
y0 = [abs(xx) for xx in x]
y1 = [xx**2 for xx in x]

# can be either the same source for all plots or different sources (as shown here) but the length of the sources should be the same
source1 = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))
source2 = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))
code1 = "source1.set('selected', cb_data['index']);"
code2 = "source2.set('selected', cb_data['index']);"
callback = CustomJS(args={'source1': source1, 'source2': source2}, code=code1+code2)

p1 = figure(tools=[], width=300, height=300, title=None, toolbar_location=None)
p2 = figure(tools=[], width=300, height=300, title=None, toolbar_location=None)
c1 = p1.circle(x='x', y='y0', source=source1)
c2 = p2.circle(x='x', y='y1', source=source2)
hover1 = HoverTool(callback=callback, renderers=[c1])
hover2 = HoverTool(callback=callback, renderers=[c2])
p1.add_tools(hover1)
p2.add_tools(hover2)

doc_layout = row([p1, p2])
curdoc().add_root(doc_layout)