首页 > 解决方案 > ReactJS 中的对象关系?

问题描述

我有一个包含对象的数组,我需要使用其中的键中的值来搜索另一个数组,例如获取项目 ID 的名称。

主数组:

this.setState({ offers: [
    {
        "name": "Hello World",
        "description": "Goodbye World",
        "item": {
            "value": 1,
            "label": "Í'm a label",
            "type": 44
        },
        "action": 2
    },
    {
        "name": "Hello World",
        "description": "Goodbye World",
        "item": {
            "value": 2,
            "label": "Í'm a label",
            "type": 44
        },
        "action": 2
    },
]});

和项目数组:

this.setState({ items: [
    {
        "id": 1,
        "name": "I'm an item!",
        "description": "I'm the item description!"
    },
    {
        "id": 2,
        "name": "I'm an item too!",
        "description": "I'm the item description too!"
    }
]});

在反应中,要显示主数组,我执行以下操作:

render() {
    return (
        <Col>
            {(this.state.offers && this.state.offers.length > 0) ? (
                this.state.offers.map(offer => this.renderOffer(offer))
            ) : (
                <p>Loading...</p>
            )}
        </Col>
    );
}

renderOffer(product) {
    console.log(product.description) // This would print "Goodbye world"
}

但这只是让我获取主数组的数据,我仍然需要列出每个项目的项目名称/项目描述。我正在寻找类似的东西product.item.name,它可以从我的第二个数组中获取name密钥,基于当前在renderOffer.

如何才能做到这一点?

标签: javascriptnode.jsreactjs

解决方案


renderOffer()只需在里面找到与该报价匹配的 id 的项目。

renderOffer(product) {
  const item = this.state.items.find(item => item.id === product.item.value)
  return (
    <ul>
      <li>{product.name}</li> // <- Hello World
      <li>{item.name}</li> // <- I'm an item!
    </ul>
  )
}

推荐阅读