我是JavaScript的新手,我在编码方面遇到了一些问题,有一个data1[]
表,看起来像这样:
data1[]
data1[0]={
"Houses": [{
"id": "house1",
"name": "Homer's house",
"rooms": [{
"id": "room1",
"name": "Chris's room",
"facilities": [{
"id": "chair1",
"name ": "chair of leather"
}
]
}]
}
}
data1[1]={
"Houses": [{
"id": "house1",
"name": "Homer's house",
"rooms": [{
"id": "room1",
"name": "Chris's room",
"facilities": [{
"id": "bed",
"name": "king size bed"
}
]
}]
}
data1[2]={
"Houses": [{
"id": "house2",
"name":"Megan's house",
"rooms": [{
"id": "room1",
"name": "Kelly's room",
"filters": [{
"id": "sofa",
"name": "corner Sofa"
}
]
}]
}]}
我想构建一个像这样的Json:
JsonArray : {
"Houses": [{
"id": "house1",
"name": "Homer's house",
"rooms": [{
"id": "room1",
"name": "Chris's room",
"facilities": [{
"id": "chair1",
"name ": "chair of leather"
},
{
"id": "bed",
"name": "king size bed"
}
]
}]
},{
"id": "haouse2",
"name":"Megan's house",
"rooms": [{
"id": "room1",
"name": "Kelly's room",
"filters": [{
"id": "sofa",
"name": "corner Sofa"
}
]
}]
}]
}
你们有没有使用JavaScript做到这一点的简单而又最优化的方法! 谢谢
答案 0 :(得分:0)
我想只有一种方法可以使用对象,您可以破坏对象中的这个复杂的json节点并在其中插入一个,但是这取决于您如何使用此数据...
使用FormData
var myForm = document.getElementById('myForm');
formData = new FormData(myForm);
formData.append('username', 'Chris');
<form id="myForm" name="myForm">
<div>
<label for="username">Enter name:</label>
<input type="text" id="username" name="username">
</div>
<input type="submit" value="Submit!">
</form>
创建Raw Json
就像您在示例中所做的一样
创建每个对象
room.id = "room1"
room.name = "Chris's room"
house = {}
house.id = "house1"
house.name" = "Homer's house"
rooms = [room]
但这取决于您如何使用它,是在后端(NODEJS)创建它的?在前端?您可以使其更“漂亮”和“可读取”,但无论如何都必须编写它,可以使它更“简单”
答案 1 :(得分:0)
是的,您可以使用Array.map
进行迭代并从data1中获取值以获取数据。
var data = {JSONArray : {Houses : data1.map(function(ele){
return ele.Houses[0]
})}}
console.log(data);