将多个键值对设置为AngularJS中键的值

时间:2018-03-28 13:06:27

标签: angularjs json javascript-objects

我试图形成一个由一个对象组成的数组,该对象的值又是一组对象数组中的一对键值对象。基本上,我尝试将数组中的一组对象(从Request JSON)作为值分配给另一个数组中的对象键(parentKey)。请帮我解决以下问题:

来源 - 对象数组:

{
  "Array": [
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    }
  ]
}

结果 - 包含一个对象的数组,该对象的值是一组键值对象对象:

{
  "Array":[{
    "parentKey": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
        }
    },{
    "parentKey": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
        }
    },{
    "parentKey": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
        }
    }]
}

2 个答案:

答案 0 :(得分:0)

只需遍历对象的Array属性,然后将parentKey对象推送到新数组中。最后,您可以将该数组设置为具有属性Array的新对象。

var input = {
  "Array":[{
    "parentKey": {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
     }
    },
    {
     "parentKey": {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
     }
    },
    {
    "parentKey": {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
     }
  }]
}

var arr = [];

input.Array.forEach((obj)=>{
  arr.push(obj.parentKey);
});
var output = {
  "Array" : arr
};

console.log(output);

答案 1 :(得分:0)

应该像这样工作。

let given={
      "Array":[{
        "parentKey": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
            }
        },{
        "parentKey": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
            }
        },{
        "parentKey": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
            }
        }]
    }

    let result={
      "Array":[]
    }

    given.Array.forEach((subArr, i)=>{
      result.Array.push(subArr.parentKey)
    })

    console.log(result)

反过来就是这样:

let given=
{
  "Array": [
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    }
  ]
}


let result={
  "Array":[]
}

given.Array.forEach((subArr, i)=>{
  result.Array.push({"parentKey":subArr})
})

console.log(result)