无论键值在数组中的何处,如何获取键值

时间:2019-10-23 19:19:07

标签: javascript arrays object

获取此 slice_type:部分。不管它在数组中的什么位置      因此这里是[1],但可能是[0]或[2]。最后,我需要获取具有slice_type的对象中的items键:'section';

  [ { slice_type: 'structure',
        slice_label: null,
        items: [ [Object] ],
        primary: {} },
      { slice_type: 'section', << Grab this slice_type section. No matter where it's in the array,
 so here its [1], but it could be [0] or [2]. in the end I need to grab the items key that are in the object that has slice_type: 'section';
        slice_label: null,
        items:
         [ [Object],
           [Object],
           [Object],
           [Object],
           [Object],
           [Object],
           [Object] ], <<- get this array of values
        primary: { headline: [Array] } }

3 个答案:

答案 0 :(得分:1)

您可以使用过滤器和映射数组功能。

let result = arrays
.filter((obj) => obj["slice_type"] === "section") // filter by condition
.map(obj => obj.items);// return items of objects in filtered list

答案 1 :(得分:0)

因为它是一个数组并在其中包含对象
因此您可以循环所有对象并检查slice_type
例如:

let listOfSliceType = []
for (let object of array) {
     if (object['slice_type'] && object['slice_type'] === 'section') {
          listOfSliceType.push(object);
     }
}

答案 2 :(得分:0)

您可以使用过滤器过滤数组并获取项目:

var objects = myArray.filter(obj => {
  return obj.slice_type === 'section'
});

var result = objects[0].items;