user3142695
user3142695

Reputation: 17352

How to replace object fields by content of nested field?

This is my object, which I need to modify:

const doc = { 
  _id: 'ZjenyEXyLChbksHqL',
  content: {
    en: [
      { 
        content: 'Content',
        timestamp: 1518811796,
        reviewed: { 
          user: '5b0b9e1153e8a750642e9caf',
          timestamp: 1518811796
        },
        finalized: { 
          user: '5b0b9e1153e8a750642e9caf',
          timestamp: 1518811796
        }
      }
    ]
  },
  reference: [ 'hp9v53uQqQPRXSYAi' ],
  main: 'XN7iqmCFD4jpgJZ6f'
}

I need to replace the content object by the first object of the en-array.

The result should look like:

{ 
  _id: 'ZjenyEXyLChbksHqL',
  content: 'Content',
  reviewed: { 
    user: '5b0b9e1153e8a750642e9caf',
    timestamp: 1518811796
  },
  finalized: { 
    user: '5b0b9e1153e8a750642e9caf',
    timestamp: 1518811796
  },
  reference: [ 'hp9v53uQqQPRXSYAi' ],
  main: 'XN7iqmCFD4jpgJZ6f'
}

My attempt looks like this:

const language = 'en'
const data = (doc && doc.content && doc.content[language] && doc.content[language][0]) || {}
doc.content = data.content
doc.reviewed = data.reviewed
doc.finalized = data.finalized

That feels not very elegant. Couldn't I use a spread-operator or something like this?

Also my problem is, that reviewed and finalized are optional. In that case I don't want to set that key. In my code I do get finalized: undefined.

Upvotes: 1

Views: 93

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138457

Object.assign(doc, ((doc.content || {})[language] || [{}])[0])

You could use Object.assign to copy all the values. That might be a bit more elegant using an utility:

const get = (obj, ...keys) => keys.reduce((obj, key) => obj[key] || {}, obj);

Object.assign(doc, get(doc, "content", language, 0));

Upvotes: 2

joelnet
joelnet

Reputation: 14261

Yes you can use the spread operator.

const data = (doc && doc.content && doc.content[language] && doc.content[language][0]) || {}

const newDoc = {
    ...doc,
    ...data
}

Upvotes: 0

Related Questions