1

I have some json data which looks like this:

{ 
'harry-test-com': { 'quoteID234324': {'day': 'tuesday', 'cost':'1000'}},
'sam-imaginarydomain-com': {
'quoteID13211': {'day': 'wednesday', 'cost': '500'},
'quoteID534534': {'day': 'monday', 'cost': '300'}
 }
};

So basically our quotes are arranged by user for easy filtering. However, on one page I'd like to display ALL the quotes in a list. So I'd like to go through each user, grab their quotes, and add them to an object sorted by keys, like this:

'quoteID234324': {'day': 'tuesday', 'cost':'1000'}, 
'quoteID13211': {'day': 'wednesday', 'cost': '500'},
'quoteID534534': {'day': 'monday', 'cost': '300'}

I think lodash would no doubt be useful for this, but I just have no clue where to begin?? Any help would be GREATLY appreciated! Cheers

1 Answer 1

1

You can reduce the object into a new object using Object.keys() and Object.assign():

const obj = {
  'harry-test-com': {
    'quoteID234324': {
      'day': 'tuesday',
      'cost': '1000'
    }
  },
  'sam-imaginarydomain-com': {
    'quoteID13211': {
      'day': 'wednesday',
      'cost': '500'
    },
    'quoteID534534': {
      'day': 'monday',
      'cost': '300'
    }
  }
};

const result = Object.keys(obj).reduce((days, user) => Object.assign(days, obj[user]), {});

console.log(result);

A less supported option is to use Object.values() with Object.assign:

const obj = {
  'harry-test-com': {
    'quoteID234324': {
      'day': 'tuesday',
      'cost': '1000'
    }
  },
  'sam-imaginarydomain-com': {
    'quoteID13211': {
      'day': 'wednesday',
      'cost': '500'
    },
    'quoteID534534': {
      'day': 'monday',
      'cost': '300'
    }
  }
};

const result = Object.assign({}, ...Object.values(obj));

console.log(result);

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

11 Comments

Amazing that's just what I needed thank you so much!
I went with the second as it's a little more concise as we may be adding quite a few keys within each object. However eslint yelled at me to use spread so I researched that and ended up with this: ` const result = Object.assign(...Object.values(obj)); `
Updated the answer to create a new object, so it won't mutate the original data ('harry-test-com' object).
Amazing! I've just been trying to figure out why my componentWillReceiveProps wasn't firing and figured it must be something to do with mutating the state! Lifesaver...
Hmm, it's still not firing. My redux reducer is structured like this: const quotes = action.payload; const quotesList = Object.assign({}, ...Object.values(quotes)); return { ...state, quotesList }; Any idea why thats not causing the componentWillReceiverProps to fire?
|

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.