0

I have this response object from an api, and I want to loop it and render it as if it was a normal array, how can I render tshirt, jeans and furniture? I will not like to render the value of sneakers, Any suggestion?

const items = {
        tshirt: "Model TS",
        jeans: "ModelXW",
        sneakers: "indcdsc54",
        furniture: "Table31S"
    };

{Object.keys(items).map=>{i => 
  <Card>
 {items[key]}
  </Card>
 }
}

1

4 Answers 4

1

Try this one implementation line:

{Object.entries(items).filter(v => v[0] !== 'sneakers').map((v, idx) => <Card key={idx}>v[1]</Card>)}
Sign up to request clarification or add additional context in comments.

2 Comments

Can I chain multiple .filter()? Just in case I do not want to render other value?
Yep! Try adding a const somewhere outside the render with the values you want to exclude, like: const toExclude = ['sneakers', 'jeans'] and then modify your filter like: filter(v => !toExclude.includes(v[0]))
1

You can read properties of an object using dynamic key: objectName[keyName]:

{
  Object.keys(items).map(key => <Card key={key}>{items[key]}</Card>)
}

and to filter out sneakers:

{Object.keys(items).filter(key => key !== 'sneakers').map((key) => (
  <Card key={key}>{items[key]}</Card>
))}

1 Comment

This will render all the values, I do not want to render the value of sneakers
1

Instead of multiple loops, add an if condition to your code:

Object.keys(items).map(key => {
  if (key != 'sneakers') {
    return(<Card>{items[key]}</Card>);
  }
});

Comments

0

We can use destructuring and it is definitely more readable.

  const { sneakers, ...rest } = items;
    
    Object.keys(rest).map((item, id) => {
      <Card key={id}>
          {item}
      </Card>
    }
    );

1 Comment

I recommend the destructuring feature in ES6 for this.

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.