1

I have grouped object inside an array according to specific property (in my case location.title).

let grouped = _.mapValues(
  _.groupBy(homes.items, "location.title"),
  x => x.map(y => _.omit(y, "location.title"))
);

Output result is as :

New York: (2) [{...}{...}]
Washington: (3)[{...}{...}{...}]

my Question is how can i map this output array and get output like this in React app.

Homes in New York : Here goes NewYork homes

Homes in Washington: Here goes Washington homes

1 Answer 1

2

You can use Object.keys on the grouped object to get an array of all the keys, and then use map on that array to render them separately.

<div>
  {Object.keys(grouped).map(key => (
    <div key={key}>Homes in {key}: {grouped[key].join(', ')}</div>
  ))}
</div>

function App() {
  const grouped = {
    'New York': ['foo', 'bar'],
    Washington: ['foo', 'bar', 'baz']
  };

  return (
    <div>
      {Object.keys(grouped).map(key => (
        <div key={key}>Homes in {key}: {grouped[key].join(', ')}</div>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

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

3 Comments

so {grouped[key]} will pull out object inside particular array and i can passed down this object to React Component as props in order to display this with all its props like images, contents etc
@IramAkhtar Yes, Object.keys(grouped) results in a new array with all the keys in grouped, so grouped[key] will be grouped['New York'] for the first iteration of map, and so on. If grouped[key] is an object, you can pass that down to another component as props if you like.
my grouped[key] resulting another array containing objects of homes like this. (2) [{...}{...}] (3) [{...}{...}{...}] I need to display this array of objects along side of each location.

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.