在对象数组中查找属性

时间:2018-01-12 12:37:37

标签: javascript

我试图在我的对象中找到一个数组:

    {setParentCategory
                    ? <Picker
                          selectedValue={setSubCategory}
                          label="Year group"
                          onChange={this.onGroupChange}
                          options={
                              categories.find(category => {
                                  category.id == setParentCategory;
                              }).options
                          }
                      />
                    : null}

我的数据是这样的:

  [ {
                    id: 0,
                    label: "Year 1",
                    value: 1,
                    options: [
                        { name: "Firm 1", id: 1 },
                        { name: "Firm 2", id: 2 },
                        { name: "Firm 3", id: 3 }
                    ]
                },
                {
                    id: 1,
                    label: "Year 2",
                    value: 2,
                    options: [
                        { name: "Firm 4", id: 4 },
                        { name: "Firm 5", id: 5 },
                        { name: "Firm 6", id: 6 }
                    ]
                },
                {
                    id: 2,
                    label: "Year 3",
                    value: 3,
                    options: [
                        { name: "Firm 7", id: 7 },
                        { name: "Firm 8", id: 8 },
                        { name: "Firm 9", id: 9 }
                    ]
                }
]

我的错误是无法读取未定义的属性'选项'。

1 个答案:

答案 0 :(得分:0)

find功能中,您需要明确return您正在创建的布尔值。

  

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

&#13;
&#13;
let categories = [{
    id: 0,
    label: "Year 1",
    value: 1,
    options: [{
        name: "Firm 1",
        id: 1
      },
      {
        name: "Firm 2",
        id: 2
      },
      {
        name: "Firm 3",
        id: 3
      }
    ]
  },
  {
    id: 1,
    label: "Year 2",
    value: 2,
    options: [{
        name: "Firm 4",
        id: 4
      },
      {
        name: "Firm 5",
        id: 5
      },
      {
        name: "Firm 6",
        id: 6
      }
    ]
  },
  {
    id: 2,
    label: "Year 3",
    value: 3,
    options: [{
        name: "Firm 7",
        id: 7
      },
      {
        name: "Firm 8",
        id: 8
      },
      {
        name: "Firm 9",
        id: 9
      }
    ]
  }
]

let options = categories.find(category => {
  return category.id == 2;
}).options

console.log(options)
&#13;
&#13;
&#13;