【问题标题】:Deeply nested data objects in multidimensional object多维对象中深度嵌套的数据对象
【发布时间】:2018-09-24 11:03:03
【问题描述】:

我有一个多维对象并使用 Vue,我试图使内部对象具有反应性。

我的对象如下所示:

data() {
   return {
       myObject: {}
   }
}

填充后的数据是这样的:

myObject: {
   1: {         // (client)
     0: "X",    // (index) : (value)
     1: "Y"
   },
   2: {
     0: "A",
     2: "B"
   }
}

如果我尝试使用:

let value = "X";
let client = 1;
let index = 1;

let obj = {};
obj[client][index] = value;
this.myObject = Object.assign({}, this.myObject, obj);

它会抛出一个错误:

TypeError:无法设置未定义的属性“0”

如果我在下面尝试,它会覆盖初始值,因为它最初将对象设置为 {}

let obj = {};
obj[index] = value;
let parentObj = {};
parentObj[client] = obj;
this.myObject = Object.assign({}, this.myObject, parentObj);

将值添加到多维对象的正确方法是什么?

【问题讨论】:

    标签: object vue.js vuejs2 vue-reactivity


    【解决方案1】:

    在 javascript 中,dim2Thing[1][1] = ... 表达式需要 dim2Thing[1] 存在。这就是您收到您提到的错误的原因。所以你可以做两个表达式,应该可以正常工作:

    dim2Thing[1] = dim2Thing[1] || {} dim2Thing[1][1] = otherThing

    对于最后一个块,您提到它“覆盖了初始值”

    我认为这里实际发生的只是Object.assign 不是递归的。它只合并顶级键。因此,如果parentObj 的密钥与this.myObj 重叠,那么子密钥将丢失。

    Object.assign({ a: { b: 2} }, { a: { c: 3 } }) // returns { a: { c: 3 }  }
    

    这就是我将您的代码解释为试图做的事情 - 尽管我目前不熟悉 vue.js,所以我不能保证它会对您的网页产生预期的结果:

    let value = "X";
    let client = 1;
    let index = 1;
    
    const newObj = Object.assign({}, this.myObject);
    // if you have lodash _.set is handy
    newObj[client] = newObj[client] || {}; // whatever was there, or a new object
    newObj[client][index] = value
    this.myObject = newObj
    

    【讨论】:

    • 非常感谢给我|| {}的视角
    【解决方案2】:

    只需使用一个数组,这就是设计的反应式。 如果您需要从模板或任何地方的数组中获取元素,只需添加一个 find 方法

    // 温度

    late
    <div v-for="(value, idx) in myArray">{{find(obj => obj.id === idx)}}</div>
    
    methods: {
      find (searchFunction) {
        return this.myArray.find(searchFunction)  
      }
    }
    

    【讨论】:

    • 感谢您的意见。由于我的结构设计,我不能使用数组,否则.find 会像魅力一样工作
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2017-08-27
    • 2018-02-14
    • 2018-11-30
    • 2023-01-13
    • 2016-06-02
    • 2019-01-29
    • 2016-05-18
    相关资源
    最近更新 更多