Javascript在for循环中创建数组

时间:2018-07-20 17:40:26

标签: javascript

我有一个json数组,格式如下。

{
  "agents": [{
      "id": "1",
      "first_name": "Stacy",
      "last_name": "Thompson",
      "fields": [{
        "name": "workphone",
        "values": {
          "answer": "8888888888"
        }
      }, {
        "name": "Industry",
        "values": {
          "answer": "computer"
        }
      }]
    },
    {
      "id": "2",
      "first_name": "Jhon",
      "last_name": "Deo",
      "fields": [{
          "name": "workphone",
          "values": {
            "answer": "9999999999"
          }
        },
        {
          "name": "market",
          "values": {
            "answer": "Outer"
          }
        }
      ]
    }
  ]
}

我想将其转换为如下所示的简单数组,因此搜索起来会更容易:

{
  "agents": [{
    "id": "1",
    "first_name": "Stacy",
    "last_name": "Thompson",
    "workphone": "8888888888",
    "Industry": "computer"
  }, {
    "id": "2",
    "first_name": "Jhon",
    "last_name": "Deo",
    "workphone": "9999999999",
    "market": "Outer"
  }]
}

我写了下面的代码,但是我得到了错误

TypeError: Cannot set property 'id' of undefined

代码如下:

    let temp = response.data.agents;
    let temparray=[];
    for(let i = 0; i < temp.length; i++) {
      let agent = temp[i];
      Object.keys(agent).forEach(function(key) {
          if(key=='fields'){
             let tempfield =  agent.fields;
             for(let j = 0; j < tempfield.length; j++) {
                 let ccs = tempfield[j];
                 Object.keys(ccs).forEach(function(keys) {
                 if(keys=='name'){
                     temparray[i][ccs.name] = ccs.values.answer;
                 }

              });
            }
          }
        else{
         temparray[i][key] = agent[key];
         });
  } 

4 个答案:

答案 0 :(得分:7)

这是一种使用对象分解的地图和归约方法,将fields分解为一个平坦的对象,然后可以将其与其他属性合并

data.agents = data.agents.map(({fields, ...rest}) => {
   fields = fields.reduce((a,{name:n,values:v}) => (a[n] = v.answer, a),{});
   return {...rest, ...fields};
});

console.log(data)
<script>
  let data = {
    "agents": [{
        "id": "1",
        "first_name": "Stacy",
        "last_name": "Thompson",
        "fields": [{
          "name": "workphone",
          "values": {
            "answer": "8888888888"
          }
        }, {
          "name": "Industry",
          "values": {
            "answer": "computer"
          }
        }]
      },
      {
        "id": "2",
        "first_name": "Jhon",
        "last_name": "Deo",
        "fields": [{
            "name": "workphone",
            "values": {
              "answer": "9999999999"
            }
          },
          {
            "name": "market",
            "values": {
              "answer": "Outer"
            }
          }
        ]
      }
    ]
  }
</script>

答案 1 :(得分:0)

const newData = data.agents.map((agent) => {
const { first_name, last_name, fields } = agent;
 return {
    first_name,
  last_name,
  workphone: fields[0].values.answer,
  market: fields[1].values.answer,
 }
});
console.log(newData);

使用映射来迭代代理。当map返回一个新数组时,我返回了.map

内的单个对象

或者您可以使用上面的答案,charlietfl的。如果您有动态字段。

答案 2 :(得分:0)

您能否尝试将temparray[i]初始化为对象

let tesp =  [{"agents":[ {"id":"1", 
 "first_name":"Stacy", 
 "last_name":"Thompson", 
  "fields":[ {"name":"workphone", "values": {"answer":"8888888888"}},    {"name":"Industry", "values": {"answer":"computer"}}]
 },  {"id":"2", 
"first_name":"Jhon", 
"last_name":"Deo", 
"fields":[ {"name":"workphone", "values": {"answer":"9999999999"}},    {"name":"market", "values": {"answer":"Outer"}}
]
}
]}];
  let temp = tesp; 
  let temparray = []; 
  for (let i = 0; i < temp.length; i++) {
    let agent = temp[i]; 
    Object.keys(agent).forEach(function (key) {
        if (key == 'fields') {
           let tempfield = agent.fields; 
           for (let j = 0; j < tempfield.length; j++) {
               let ccs = tempfield[j]; 
               Object.keys(ccs).forEach(function (keys) {
               if (keys == 'name') {
                   temparray[i][ccs.name] = ccs.pivot.answer; 
               }

            }); 
          }
        }
      else {
          temparray[i] = {};
       temparray[i][key] = agent[key]; 
      }
    }); 
    console.log(temparray);
    }

答案 3 :(得分:0)

function convert() {
  let asArray = Object.values( input )[0];
  for( let i in asArray) {
    for( let j in asArray[i].fields ) {
      asArray[i][asArray[i].fields[j].name] = Object.values(asArray[i].fields[j].values).join(',');
    }
    delete asArray[i].fields;
  }
  // console.log(asArray);
  return {'agents': asArray};
}

var input = {
  "agents": [{
      "id": "1",
      "first_name": "Stacy",
      "last_name": "Thompson",
      "fields": [{
        "name": "workphone",
        "values": {
          "answer": "8888888888"
        }
      }, {
        "name": "Industry",
        "values": {
          "answer": "computer"
        }
      }]
    },
    {
      "id": "2",
      "first_name": "Jhon",
      "last_name": "Deo",
      "fields": [{
          "name": "workphone",
          "values": {
            "answer": "9999999999"
          }
        },
        {
          "name": "market",
          "values": {
            "answer": "Outer"
          }
        }
      ]
    }
  ]
};

console.log( convert( input ) );
Desired output:
<pre style="height: 200px; overflow: scroll;">
{
  "agents": [{
    "id": "1",
    "first_name": "Stacy",
    "last_name": "Thompson",
    "workphone": "8888888888",
    "Industry": "computer"
  }, {
    "id": "2",
    "first_name": "Jhon",
    "last_name": "Deo",
    "workphone": "9999999999",
    "market": "Outer"
  }]
}
</pre>