简体   繁体   English

将JavaScript数组转换为JSON格式:JavaScript

[英]Converting JavaScript Array To JSON Format:JavaScript

i have an array like this coming back response from the server: 我有一个像这样的数组从服务器返回响应:

[
    [
        "111",
        1
    ],
    [
        "1010",
        4
    ],
    [
        "111",
        5
    ],
    [
        "1010",
        6
    ],
    [
        "1010",
        7
    ]
]

i want to convert it into a JavaScript JSON like this: 我想将其转换为JavaScript JSON,如下所示:

[
 {
    "branch":  "111",
    "id":1

 },
 {
    "branch":  "1010",
    "id":4
 },
 {
    "branch":  "111",
     "id":5
 },
 {
    "branch":  "1010",
     "id":6
 },
 {
    "branch":  "1010",
     "id":7
 }
]

If any one can help it will be much appreciable. 如果有任何人可以帮助的话,那将是非常可观的。 Bcs i am new to javascript BCS我是javascript新手

Explanation: 说明:

You can do this with Array#map and destructuring . 您可以使用Array#mapdestructuring进行此操作

Destructuring : 销毁

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. 解构赋值语法是一种JavaScript表达式,可以将数组中的值或对象中的属性解压缩为不同的变量。

Array#map : Array#map

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。

Solution: 解:

 const data = [["111",1],["1010",4],["111",5],["1010",6],["1010",7]]; const res = data.map(([branch,id])=>({branch,id})); res.sort((a,b)=>a.id-b.id); console.log(res); 

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

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