【问题标题】:parse all the values from the json array using typescript使用打字稿解析json数组中的所有值
【发布时间】:2021-09-23 08:35:39
【问题描述】:

我有一个像下面这样的 json 数组,我需要从下面的数组中获取所有值,并且需要形成一个新的 数组对象数组

但我不能使用任何模型文件来实现这一点。不确定如何在打字稿中执行此操作。

请帮帮我。

[
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
]

我需要像这样输出

[["Rajesh","Kumar","25"],["john","david","26"]]

【问题讨论】:

  • 这里与 Typescript 无关。你可以用 JS Array#map + Object.values() 来做到这一点。试试:inputArray.map(obj => Object.values(obj)).

标签: arrays json angular typescript


【解决方案1】:

因此,您要做的是使用<Array>.map 映射数组中的所有值。然后您可以通过 2 种方式将对象作为数组返回,首先是使用 <Object>.values 或仅使用 [obj.firstName, obj.lastName, obj.age]

您可以尝试循环遍历数组并使用 for 循环更改值,但它确实很冗长。我推荐第一种方法,因为在这种情况下它更具动态性。

所以生成的代码将是

let data = [
  {
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "age": "25"
  },
  {
    "firstName": "john",
    "lastName": "david",
    "age": "26"
  }
];
// I'm assigning the value to the variable called data in this case

data = data.map(item => Object.values(item));

// Now the value of data is the array you want it to be

现在您可以按照我指定的其他方法进行操作,但这是最不冗长的方法。

【讨论】:

    【解决方案2】:

    这将为您提供所需的内容

    const array = [
      {
        "firstName": "Rajesh",
        "lastName": "Kumar",
        "age": "25"
      },
      {
        "firstName": "john",
        "lastName": "david",
        "age": "26"
      }
    ];
    
    // Under result you will have the required array
    const result = a.map(x => [Object.keys(x).map(key => x[key])])
    
    // Or, explicit
    const result = array.map(x => [x.firstName,x.lastName,x.age])
    

    【讨论】:

      【解决方案3】:

      由于每个对象内的元素有限,您可以这样做:

      const collections = [
        {
          firstName: 'Rajesh',
          lastName: 'Kumar',
          age: '25'
        },
        {
          firstName: 'john',
          lastName: 'david',
          age: '26'
        }
      ]
      
      const answer = collections.map(c => [c.firstName, c.lastName, c.age])
      console.log(answer)
      

      【讨论】:

        【解决方案4】:

        你可以试试这个:

        let newArrObj: any[] = []; 
        
        // objects - your array of objects
        
        for (let obj in objects) {
        
          let objArray= []; 
          objArray.push(obj.firstName)
          objArray.push(obj.lastName)
          objArray.push(obj.age)
          
          newArrObj.push(objArray);
         }
         
         console.log("Result newArrObj: ", newArrObj);

        【讨论】:

          猜你喜欢
          • 2019-01-13
          • 2023-02-03
          • 2020-05-23
          • 2019-02-13
          • 2018-09-07
          • 2016-11-01
          • 2018-08-29
          • 1970-01-01
          • 2022-11-19
          相关资源
          最近更新 更多