0

I have an array with objects, and I need to use a value from a key inside of it to search another array, like getting the name of the item ID.

The main array:

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
    },
]});

And the item array:

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!"
    }
]});

In react, to display the main array, I do the following:

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"
}

But this only let's me get the data of the main array, and I still need to list the item name/item description of every item. I'm looking for something like product.item.name which would get the name key from my second array, based on the ID that is currently listed in each item in renderOffer.

How can this be done?

1 Answer 1

3

Inside renderOffer() just find the item with the id that matches that offer.

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>
  )
}
Sign up to request clarification or add additional context in comments.

1 Comment

OP could also apply your answer to reduce the initial offers array into a new easy-to-use collection that includes the item inlined in each offer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.