【问题标题】:To place values of object from key value pair in an array in javascript将键值对中的对象值放在javascript中的数组中
【发布时间】:2021-03-11 23:07:31
【问题描述】:

我有一个对象

{
 "input":{
  "id": "7879",
  "inputType": "9876",
  "streamName": "870"
  },
 "transformation":{
   "id": "7",
   "dependencies": [
          "8i"
    ],
   "dropColumns": "hkj",
   "processor": "hgf"
 },
 "output": {
   "id": "v",
   "saveMode": "uyt",
   "dependentIds": [
        "h"
    ],
   "outPartition":[
        "hg"
    ]
 }
}

基本上每个离开键的值我都必须把它放在一个数组中。所以输入、转换、输出值(都是对象)应该放在数组里面。

预期输出:

{
 "input": [
  {
  "id": "7879",
  "inputType": "9876",
  "streamName": "870"
  }
  ],
 "transformation":[
   {
   "id": "7",
   "dependencies": [
          "8i"
    ],
   "dropColumns": "hkj",
   "processor": "hgf"
 }
 ],
 "output":[
   {
   "id": "v",
   "saveMode": "uyt",
   "dependentIds": [
        "h"
    ],
   "outPartition":[
        "hg"
    ]
 }
 ]
}

我尝试使用 for in 循环进行迭代,但无法达到预期的输出我应该如何将值(对象)放在数组中

var arr = [];
for(key in obj){
  arr.push(Object.assign(obj[key],{name: key}))
}

【问题讨论】:

  • 为什么是arr?为什么Object.assign()?为什么{name: key}
  • 为什么要改变这个结构?它完全可以用于任何目的。

标签: javascript arrays object for-in-loop


【解决方案1】:

你的意思是这个(虽然不确定你为什么需要这个)?

const input = {
 "input":{
  "id": "7879",
  "inputType": "9876",
  "streamName": "870"
  },
 "transformation":{
   "id": "7",
   "dependencies": [
          "8i"
    ],
   "dropColumns": "hkj",
   "processor": "hgf"
 },
 "output": {
   "id": "v",
   "saveMode": "uyt",
   "dependentIds": [
        "h"
    ],
   "outPartition":[
        "hg"
    ]
 }
}
Object.keys(input).forEach(key => input[key] = [input[key]] )
console.log(input)

【讨论】:

    【解决方案2】:

    根据您提供的对象的输出,循环元素并将键创建为数组的简单实现可以是:

    for(key in obj){
      obj[key] = [obj[key]];
    }
    

    【讨论】:

      【解决方案3】:

      如果你想让它不可变,你可以使用 reduce 函数重建它:

      reduce() 方法对数组的每个元素执行(您提供的)reducer 函数,从而产生单个输出值。

      更多信息见:MDN Webdocs - reduce()

      const data = {
       "input":{
        "id": "7879",
        "inputType": "9876",
        "streamName": "870"
        },
       "transformation":{
         "id": "7",
         "dependencies": ["8i"],
         "dropColumns": "hkj",
         "processor": "hgf"
       },
       "output": {
         "id": "v",
         "saveMode": "uyt",
         "dependentIds": ["h"],
         "outPartition":["hg"]
       }
      };
      
      const customFormat = (data) => Object.keys(data).reduce((object, key) => {
          object[key] = [data[key]];
        return object
      }, {});
      
      console.log(customFormat(data));

      【讨论】:

        猜你喜欢
        • 2018-09-11
        • 1970-01-01
        • 2010-10-15
        • 2014-07-09
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多