简体   繁体   English

如何将json映射转换为数组? 角

[英]how to convert json map to array ? Angular

I have the json like follow example, i would like to convert this json map to array for to be able to loop on it.我有像下面这样的 json 示例,我想将此 json 映射转换为数组,以便能够对其进行循环。

I use the Object.keys method but I don't know how to have a key => value format for the whole json.我使用 Object.keys 方法,但我不知道如何为整个 json 设置键 => 值格式。 I need to get the keys to make a table I know there is the pipe keyvalue but it's not what I need.我需要获取键来制作表格我知道有管道键值,但这不是我需要的。 or maybe I use it wrong或者我用错了

example json示例 json

{
  "pays": "UK"
  "test": [
   [
    "123456", // here i want key id
    "blabla", // here i want key name 
    "lorem ipsum" // here i want key type
   ],
   [
    "654321",
    "ipsum",
    "blabla"
   ]
  ]
}

components.ts组件.ts

get() {
 this.myService.getUrl().subscribe(data => {
  this.myArray = Object.keys(data).map((key) => {
   return {
    id: key,
    name: data[key]
   }
  }):
 }

Please try this请试试这个

var input: any = {
      "pays": "UK",
      "test": [
       [
        "123456", // here i want key id
        "blabla", // here i want key name 
        "lorem ipsum" // here i want key type
       ],
       [
        "654321",
        "ipsum",
        "blabla"
       ]
      ]
    }

    input .test = input.test.map((item: any) => {

      return {
        id: item[0],
        name : item[1],
        type : item[2]
      }
    })

This is one possible solution to transform array of strings into array of JSONs:这是将字符串数组转换为 JSON 数组的一种可能解决方案:

 let input = { pays: "UK", test: [ [ "123456", "blabla", "lorem ipsum" ], [ "654321", "ipsum", "blabla" ] ] }; let result = {}; result.pays = input.pays; result.test = []; for (let i = 0; i < input.test.length; i++){ let testEl = input.test[i]; let resultObj = {}; resultObj.id = testEl[0]; resultObj.name = testEl[1]; resultObj.type = testEl[2]; result.test.push(resultObj); } console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM