0

I got an array with following data structure:

[
  { 
    _id: 'dgPMHw3ivRSp3wyWe',
    content: { 
      en: [{ content: 'foo', extended: 'bar' }, {...}],
      it: [{ content: 'any', extended: 'thing' }, {...}]
    },
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  },
  {...}
]

I need to modify this array to get only string values for content by selecting the first element of a specific language.

So for the english language the result should be:

[
  { 
    _id: 'dgPMHw3ivRSp3wyWe',
    content: 'foo',
    extended: bar,
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  }
]

I know I could get the string with

const language = 'en'
array.forEach(doc => {
  console.log(doc.content[language][0].content)
  console.log(doc.content[language][0].extended)
})

But how do I replace it to get my result?

1
  • Did you look at my answer....? Just curious. Commented Dec 9, 2017 at 2:45

2 Answers 2

3

Here's how without having to list each property:

var array = [{
  _id: 'dgPMHw3ivRSp3wyWe',
  "content": {
    en: {
      content: 'foo',
      extended: 'bar'
    },
    it: {
      content: 'any',
      extended: 'thing'
    }
  },
  order: 1,
  parent: 'Dn59y87PGhkJXpaiZ'
}];

const language = "en";
array = array.map(doc => {
  doc = Object.assign(doc, doc.content[language]);
  return doc;
});
console.log(array);

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

2 Comments

The language elements are array, so I used doc.content[language][0]
@user3142695 I don't know what else is in those arrays, but my code retains all the en information, regardless of its structure.
3

You can do so:

  let result = data.map(e => ({
        ...e, 
        content: e.content[language].content,
        extended: e.content[language].extended
  }));

1 Comment

I do get a syntax error: Unexpected token for ...e

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.