1

I have and array of objects which I would like to transform into single js object. The array contains target value and array of keys. Note: I want this to work in vanilla js without importing scripts.

The source array:

[ 
  { value: 'res-1', keys: [ 'first' ] },
  { value: 'res-2', keys: [ 'second', 'deeperOne' ] },
  { value: 'res-3', keys: [ 'second', 'deeperTwo' ] },
  { value: 'res-4', keys: [ 'second', 'deeperThree', 'moreDeeper' ] },
  { value: 'res-5', keys: [ 'third' ]} 
 ]

Desirable result (object):

{
  first: 'res-1',
  second: {
    deeperOne: 'res-2',
    deeperTwo: 'res-3',
    deeperThree: {
      moreDeeper: 'res-4'
    }
  },
  third: 'res-5'
}

2
  • youmightnotneed.com/lodash#set might help. loop through array and use keys.join('.') to create path. Commented Jul 24, 2022 at 19:39
  • And there even is Plain js code. Please post this as answer, so I could give you some points! Commented Jul 24, 2022 at 19:50

1 Answer 1

1

cmgchess gave answer to the question with a comment. Here is the code!

const array = [ 
  { value: 'res-1', keys: [ 'first' ] },
  { value: 'res-2', keys: [ 'second', 'deeperOne' ] },
  { value: 'res-3', keys: [ 'second', 'deeperTwo' ] },
  { value: 'res-4', keys: [ 'second', 'deeperThree', 'moreDeeper' ] },
  { value: 'res-5', keys: [ 'third' ]} 
 ]

const set = (obj, path, value) => {
  path.reduce((acc, key, i) => {
    if (acc[key] === undefined) acc[key] = {}
    if (i === path.length - 1) acc[key] = value
    return acc[key]
  }, obj)
}

let object = {}
array.forEach(({value, keys}) => set(object, keys, value))

console.log(object)

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.