JavaScript通过键列表更新JSON值。

huangapple go评论67阅读模式
英文:

javascript update json value by list of keys

问题

我有一个对象,它非常深。例如:

section: {
    data: {
        x = 4
    }
}

真实的情况甚至更加深层。

当我有这样一个函数时,如何更新 x 的值:

const keys = [section, data, x];
const update = (newValue, keys) => {
    // 应该是这样的
    // myObjc[section][data][x] = newValue;
}
英文:

I have an object which goes so deep. For example:

section: {
     data: {
          x = 4
     }
}

Real one is even more deep.

How can I update the x value when I have such a function:

const keys = [section, data, x];
const update = (newValue, keys) => {
      // it should be like this
      // myObjc[section][data][x] = newValue;
}

答案1

得分: 1

JavaScript通过键列表更新JSON值。

我认为你需要的是一个深度设定值的函数,就像这样

const update = (newValue, keys, obj) => {
    for(const key of keys.slice(0,-1))
        obj=obj[key];
    obj[keys[keys.length-1]]=newValue
}
英文:

JavaScript通过键列表更新JSON值。

I think what you need is a deep set value function, like this

const update = (newValue, keys, obj) => {
    for(const key of keys.slice(0,-1))
        obj=obj[key];
    obj[keys[keys.length-1]]=newValue
}

答案2

得分: 1

你可以使用递归函数来避免错误。

/**
 * 安全地在对象中设置一个键或抛出可预测的错误
 * @param obj 一个对象
 * @param path 表示路径的字符串数组
 * @param value 新值
 */

function safeUpdateObject(obj, path, value){
  if(path.length === 0){
    throw new Error('无法更新没有路径的对象');
  }
  if(path.length === 1){
    obj[path[0]] = value;
    return;
  }
  if(path.length > 1){
    if(typeof obj[path[0]] === 'undefined'){
      obj[path[0]] = {};
    }
    if (typeof obj[path[0]] !== 'undefined' && typeof obj[path[0]] !== "object") {
      throw new Error('无法在非对象上设置键值对');
    }
    let unwrapped = obj[path[0]];
    safeUpdateObject(unwrapped, path.slice(1), value);
  }
}
英文:

You can use a recursive function to avoid errors

/**
 * Safely sets a key in an object or throws a predictable error
 * @param obj An object
 * @param path An Array of strings representing the path
 * @param value The new value
*/

function safeUpdateObject(obj, path, value){
  if(path.length === 0){
    throw new Error('Cannot update object with no path');
  }
  if(path.length === 1){
    obj[path[0]] = value;
    return;
  }
  if(path.length > 1){
    if(typeof obj[path[0]] === 'undefined'){
      obj[path[0]] = {};
    }
    if (typeof obj[path[0]] !== 'undefined' && typeof obj[path[0]] !== "object") {
      throw new Error('Cannot set key-value pair on non-object');
    }
    let unwrapped = obj[path[0]];
    safeUpdateObject(unwrapped, path.slice(1), value);
  }
}

答案3

得分: 1

const o = {section: {data: {  x: 4 }} }

const keys = ['section', 'data', 'x'];
const update = (newValue, keys, obj) => {
      const l = keys.reduce((acc, x, i) => {
            if (i == keys.length - 1) {
                  acc[x] = newValue
            }
            return acc[x]
      }, obj)
      obj = l
}

update(5, keys, o)
英文:
const o = {section: {data: {  x: 4 }} }

const keys = ['section', 'data', 'x'];
const update = (newValue, keys, obj) => {
      const l = keys.reduce((acc, x, i) => {
            if (i == keys.length - 1) {
                  acc[x] = newValue
            }
            return acc[x]
      }, obj)
      obj = l
}

update(5, keys, o)

huangapple
  • 本文由 发表于 2023年3月3日 21:48:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定