jadeallencook
jadeallencook

Reputation: 686

Merging Objects Using Vanilla JavaScript

I've been working on an event handler to sync inputs with the state and came up with this solution:

https://gist.github.com/jadeallencook/678869f988bd65378d819496c4343e78

The handler pushes the value to the end point using the string and merges the result with the current state but I have to use lodash to accomplish it, is there anyway to do it in vanilla?

Upvotes: 0

Views: 82

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386540

You could store the last key and reduce only the keys before. Ath the end store the previous value and assign the new value.

function setValue(object, keys, value) {
    var last = keys.pop(),
        temp = keys.reduce((o, k) => o[k] = o[k] || {}, object);

    temp.original = !(last in temp) ? null : temp[last];
    temp[last] = value;
}

const
    object = {},
    path = 'foo-bar-num',
    value = 'Woo hoo!';

setValue(object, path.split('-'), value);

console.log(object);

Upvotes: 0

Raja Jaganathan
Raja Jaganathan

Reputation: 36117

Alternatively you can try lodash set function to set value for deeply nested object.

    import set from 'lodash/set'

    let path = 'foo-num';
    const paths = path.split('-').join('.')
    const value = 'some value';

    set(object, paths, value)

Upvotes: 0

ic3b3rg
ic3b3rg

Reputation: 14927

A reduce will produce a generic solution:

const path = 'foo-bar-num';
const paths = path.split('-');
const object = {};
const value = 'Woo hoo!';

paths.reduce(([object, value], path, idx) => {
  object[path] = idx === paths.length - 1 ? value : {};
  return [object[path], value];
}, [object, value]);

console.log(object)

Upvotes: 1

Related Questions