Iterating over JSON parent sections, testing for action and then returning payload

Issue

given this json structure:

{
  users: [ { action: 'add', payload: [Array] } ],
  categories: [ { action: 'add', payload: [Array] } ],
  products: [ { action: 'add', payload: [Array] } ]
}

How would you use .map() or Object.keys or similar ES6 goodness to iterate through each node (users, categories, products), and then get the "add" action (so i can if/then to different operations) and also the contents of the payload array for each section?"

Solution

If you are just interested in the values, you can use Object.values:

const data = {
  users: [ { action: 'add', payload: [Array] } ],
  categories: [ { action: 'add', payload: [Array] } ],
  products: [ { action: 'add', payload: [Array] } ]
};

Object.values(data).forEach(([{ action, payload}]) => // do anything with them);

If you need the keys as well, try Object.entries:

Object.entries(data).forEach(([key, [{ action, payload}]]) => // same );

Answered By – moonwave99

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.