想要在Node js

时间:2017-08-16 04:25:26

标签: javascript arrays json node.js object

我想将数组转换为Nodejs中的重复键对象。以下是我的数组数据

{
    "name" : "ashesh",
    "address_data" : [
        {
            "city" : "Mumbai",
            "pincode": "400097"
        },
        {
            "city" : "Delhi",
            "pincode": "1000001"
        }
    ]
}

想要将数组转换为以下对象

{
    "name" : "ashesh",
    "address_data" : {
        "address" : {
            "city" : "Mumbai",
            "pincode": "400097"
        },
        "address" : {
            "city" : "Delhi",
            "pincode": "1000001"
        }
    }
}

如何在节点js或javascript中实现此结构。请帮帮我。我知道这不是一个有效的JSON,但想转换上面的结构。我坚持要实现这种结构。

1 个答案:

答案 0 :(得分:1)

如果某些第三方仍然需要重复键,而是以JSON对象的格式创建一个字符串并发送它们。 请记住,此字符串不符合JSON,您无法解析它。

var a = { 
"name" : "ashesh", 
"address_data" : [ 
{ 
"city" : "Mumbai", 
"pincode": "400097" 
}, 
{ 
"city" : "Delhi", 
"pincode": "1000001" 
} 
] 
} 

var b = `{"name": "${a.name}", "address_data": {`; 

a.address_data.forEach((x) => b = b + `"address": ${JSON.stringify(x)}`); 
b = b + "}}"; 
b = b.replace(/\}"address"/g, `},"address"`);
res.send(b);