【问题标题】:Loop through nested objects from string input [duplicate]循环遍历来自字符串输入的嵌套对象[重复]
【发布时间】:2019-07-03 13:49:22
【问题描述】:

假设我有一个类似'user.data' 的字符串,我想创建这个对象的data 字段:

const obj = {
  user: {
    data: {}
  }
}

我无法正常使用此字符串 (obj['user.data'] = {}) 执行此操作,因为它会执行此操作:

const obj = {
  user: {},
  'user.data': {}
}

这不是我想要的。

当对象是字符串的最后一部分时,我将如何使用对象创建属性?

const str = 'user.hobbies';
const obj = { user: {} };
addInNestedProp(str, obj);
console.log(obj);
// => { user: { hobbies: {} } }

【问题讨论】:

  • 对不起,但我完全不知道你在“问”什么......首先因为这里似乎没有问题......其次因为你说的很简单对我来说没有任何意义。
  • 要拥有 hello.world.there 你需要hello = { world: { there: {} } }
  • 我在搞这个。它还没有完成,但也许对你有用:pastebin.com/hhbjzrPS
  • 这不是重复的。 OP 正在询问如何使用具有特定模式的字符串通过添加该字符串中表示的属性/值来改变现有对象。

标签: javascript loops object


【解决方案1】:

这是一个解决方案,它允许您获取诸如“user.hobbies”之类的字符串,根据该字符串评估对象,并将任何属性添加到字符串中的对象,但不在对象中。

使用您的输入字符串“user.hobbies”将产生:

 {
  "name": "me",
  "user": {
    "avatarURL": "longURL",
    "hobbies": {}
  }
}

你也可以用“user.hobbies.sports.basketball”试试这个,它会产生你期望的对象层次结构。

代码有大量文档:

const existing = { name: 'me', user: { avatarURL: 'longURL' }};
const addInHobbyString = 'user.hobbies';

const newObject = addInObject(addInHobbyString, existing);

console.log(newObject);

function addInObject(term, obj) {
  // make a clone of the object 
  let objCopy = JSON.parse(JSON.stringify(obj));
  // separate serach terms
  let terms = term.split('.');
  // set temp obj to first search term as object property
  // any modifications to temp will be seen in objCopy
  let temp = objCopy[`${terms[0]}`];
  // Find the last search term that exists as an object property
  let q = terms.reduce((acc, curr, idx) => (objCopy[`${curr}`]) ? null : idx, 0);
  // Do the work
  for (let i = 1; i <= q; i++) {
    // if property doesn't exist on object create it and set it to an empty object
    if (!temp[`${terms[i]}`]) {
      temp[`${terms[i]}`] = {};
      // Set the search depth in our temp object to the next depth
      temp = temp[`${terms[i]}`]
    }
  }
  return objCopy;
}

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 1970-01-01
    • 2013-05-06
    • 2017-05-12
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多