0

I'm wondering what the best way would be to transform my javascript array with objects. I have tried making a fancy chain with lodash but I can't figure it out.

I need to format the data this way because of the way the backend works.

// from:
var something = [
  {
    name: 'foo',
    stuff: [
      {
        id: 1
      },
      {
        id: 2
      },
      {
        id: 3
      }
    ]
  },
  {
    name: 'bar',
    stuff: []
  },
  {
    name: 'baz',
    stuff: [
      {
        id: 7
      },
      {
        id: 8
      }
    ]
  }
];

// to:
var transformed = [
  {
    name: 'foo',
    included: {
      included: [1, 2, 3]
    }
  },
  {
    name: 'bar',
    included: {
      included: []
    }
  },
  {
    name: 'baz',
    included: {
      included: [7, 8]
    }
  }
];
1
  • You really need to have added the code you've tried. Commented Apr 6, 2016 at 15:40

2 Answers 2

2

You can do this quite concisely with two map calls (the array built in or lodash's map), one nested to handle the "included" array within each object:

const transformed = something.map(it => {
  return {
    name: it.name,
    included: {
      included: it.stuff.map(thing => thing.id)
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

1

No need for lodash, just use the Array.prototype.map function:

// Sorry no fancy ES6 => here :S
var res = something.map(function(item) {
  item.included = {included : item.stuff.map(function(i) {return i.id})}
  delete(item.stuff)
  return item
})

Per @ssube's comment:

var res = something.map(function(item) {
  return {
    included : {included : item.stuff.map(function(i) {return i.id})},
    name: item.name
  }
})

See this fiddle

1 Comment

This is going to mutate the original objects, which map should not do (see this output). Rather than modifying and returning item, you probably want to return a new object with the right properties.

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.