在创建子对象的同时添加键/值对

时间:2017-02-08 09:35:22

标签: javascript object

我是处理对象的新手。我想:

  1. 添加密钥
  2. 向该键添加子对象
  3. 将键/值对推送到此子对象。
  4. 例如,我希望实现的数据结构是:

    invalidFields = {
        "_0" : {
            "firstName" : "foo",
            "lastName" : "la",
        }
    }
    

    通过迭代和比较来添加最嵌套的键/值对,因此实质上它需要添加到" _0"而不是覆盖它。

    到目前为止,我有:

    let invalidFields = {}; // this is initialised outside of the for loop
    ...
    const field = "foo";
    const passengerIdentifier = "_" + passengerIndex; // "_0"
    const fieldKey = "firstName";
    invalidFields[passengerIdentifier] = field;
    

    这会添加"firstName": "foo"的键/值对,但是当循环继续时,它会覆盖它,因此我获得的数据仅被field应用:

    invalidFields = {
        "_0" : "foo",
    }
    

    这显然不正确,因为我需要将键/值对添加到"_0"子对象。我做错了什么?

    编辑:这是我现在所拥有的一个例子,但这似乎不起作用,字段部分没有添加:

    const passengerIdentifier = '_'+passengerIndex;
    if (!invalidFields[passengerIdentifier]) {
        Object.assign(invalidFields, { [passengerIdentifier] : '' });
        Object.assign(invalidFields[passengerIdentifier], { [fieldKey]: field });
    }
    

4 个答案:

答案 0 :(得分:2)

要为每个子对象添加键/值对,请使用以下方法:

...
var field = "foo",
    passengerIdentifier = "_" + passengerIndex, // "_0"
    fieldKey = "firstName";

// assuring sub-object with certain `passengerIdentifier`
invalidFields[passengerIdentifier] = invalidFields[passengerIdentifier] || {};
invalidFields[passengerIdentifier][fieldKey] = field;

答案 1 :(得分:1)

您可以使用Object.assign并将新键/值添加到循环中的现有对象。

// outside of the loop
invalidFields[passengerIdentifier] = {};

// inside of the loop
Object.assign(invalidFields[passengerIdentifier], { [fieldKey]: field });

为了完整起见,可以直接为对象分配值

// inside of the loop
invalidFields[passengerIdentifier][fieldKey] = field;

答案 2 :(得分:1)

    let invalidFields = {}; // this is initialised outside of the for loop
    ...
    const field = "foo";
    const passengerIdentifier = "_" + passengerIndex; // "_0"
    const fieldKey = "firstName";

    var subObject = {
         'key1' : value1,
         'key2' : value2,
         // add all keys
     }

    invalidFields[passengerIdentifier] = subObject ;

答案 3 :(得分:0)

这是否符合您的目标?

invalidFields[passengerIdentifier] = { 
  [fieldKey]: field 
}