object assign keypath value

2019-05-31  本文已影响0人  peerben

实现一个函数, 该函数接收一个obj, 一个path, 一个value, 实现obj[path] = value, obj类似json格式

function assignKeyPath(obj, path, value) {
  const pathList: string[] = path.split('.');

  let assign = obj;
  while (pathList.length > 0) {
    const key = pathList.shift();

    if (pathList.length === 0) {
      assign[key] = value;
      break;
    }

    // assign[key] = assign[key] || {};
    assign = typeof assign[key] === 'object' ? assign[key] : (assign[key] = {});
  }

  return obj;
}

const obj = assignKeyPath({}, 'aa.bb.cc', 'hello');
const obj1 = assignKeyPath({aa: {dd: 1}}, 'aa.bb.cc', 'hello');
const obj2 = assignKeyPath({aa: 1}, 'aa.bb.cc', 'hello');
console.log(`obj ${JSON.stringify(obj)}`);
console.log(`obj ${JSON.stringify(obj1)}`);
console.log(`obj ${JSON.stringify(obj2)}`);
Screen Shot 2019-05-31 at 7.23.14 AM.png
上一篇下一篇

猜你喜欢

热点阅读