0
const data = {
  apple: {
    type: 'fruit',
    image: './fruit/apple.jpg'
  },
  orange: {
    type: 'fruit',
    image: './fruit/orange.jpg'
  }
  carrrot: {
    type: 'vegetable',
    image: './vegetable/carrot.jpg'
  }
}

I am trying to build a search function to loop through an object to return the items I need.

for example, if I want all the fruit, the image of apple and orange will be rendered.

I need something like this:

list = []
for item in data:
    if item.type == 'fruit':
        list.append(item)
return list

What is the proper code in React Native? Thanks in advance.

1
  • first check whether you data is valid JSON Commented Aug 9, 2018 at 5:57

2 Answers 2

1

Object.keys allow to iterate over properties:

const fruits = Object.keys(data).filter(key => data[key].type === 'fruit')
.map(key => data[key]);

First, we make an array of object properties, then we filter the keys for type fruit, And finally map the key to the object to provide an array of fruits.

Sign up to request clarification or add additional context in comments.

Comments

1
//Input 
const data = {
 apple: {
  type: 'fruit',
  image: './fruit/apple.jpg'
  },
  orange: {
    type: 'fruit',
    image: './fruit/orange.jpg'
  },
  carrrot: {
    type: 'vegetable',
    image: './vegetable/carrot.jpg'
  }
}

var expectedResult =  Object.values(data).filter((item)=>  item.type === "fruit")

Comments

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.