Javascript 如何获取键值,无论它位于数组中的何处

Javascript 如何获取键值,无论它位于数组中的何处,javascript,arrays,object,Javascript,Arrays,Object,抓取这个切片,类型:节。无论它在阵列中的什么位置, 这里是[1],但可以是[0]或[2]。最后,我需要获取具有slice_类型的对象中的items键:“section” [ { slice_type: 'structure', slice_label: null, items: [ [Object] ], primary: {} }, { slice_type: 'section', << Grab this slice

抓取这个切片,类型:节。无论它在阵列中的什么位置, 这里是[1],但可以是[0]或[2]。最后,我需要获取具有slice_类型的对象中的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] } }

因为它是一个数组,里面有对象 所以您可以循环所有对象并检查切片类型 例如:

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

可以使用过滤器和映射数组函数

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

您可以使用筛选器筛选阵列并获取项目:

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

var result = objects[0].items;