1

Code:

module.exports.set = function (data, key, value) {
    if (key.includes(".")) {
  
      let elements = key.split(".");
      let element = elements.pop();
      let obj = elements.reduce((object, keyy) => {
        if (typeof object[keyy] == "undefined") object[keyy] = {};
  
        return object[keyy];
      }, data);
  
      obj[element] = value;
  
      return data;
    } else {
      data[key] = value;
  
      return data;
    }
}

I'm going to explain the problem to you with examples.

var obj = {};

set(obj, "hello.world", "test")

console.log(obj)

The console log:

{
    "hello": {
        "world": "test"
    }
}

But if I write this code:

var obj = {
    "hello": {
        "world": "test"
    }
};

set(obj, "hello.world.again", "hello again")

console.log(obj)

There is no change in the object. The console log will be this:

var obj = {
    "hello": {
        "world": "test"
    }
};

I wanna the result like this:

{
    "hello": {
        "world": {
            "again": "test"
        }
    }
}

In lodash module, I can do the I told things. But in my code I can't do that. Please help me, how can I do this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
croxy
  • 19
  • 1
  • 4

2 Answers2

0

My guess would be that you're looking for

if (typeof object[keyy] != "obect")

instead of the

if (typeof object[keyy] == "undefined")

which will not detect the string that's currently the property value.

Of course the call set(obj, "hello.world.again", "hello again") would lead to {"hello": {"world": {"again": "hello again"}}}, not to {"hello": {"world": {"again": "test"}}}.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

I found your logic is expecting a JSON object but receiving string value, it needs to modify a little bit or set value like this {again: 'hello again'}.

I tried to write this set method in short, it may help someone!

function set(obj, key, value) {
  let keys = key.split('.');
  if(keys.length<2){ obj[key] = value; return obj; }

  let lastKey = keys.pop();

  let fun = `obj.${keys.join('.')} = {${lastKey}: '${value}'};`;
  return new Function(fun)();
}

var obj = {
    "hello": {
        "world": "test"
    }
};

set(obj, "hello.world.again", 'hello again'); // Value should be object here
console.log(obj);

set(obj, "hello.world.again.onece_again", 'hello once again');
console.log(obj);
Arun Saini
  • 6,714
  • 1
  • 19
  • 22