[英]Convert array to nested object structure using Javascript
I am trying to convert one array of object to one nested object structure using Javascript
but the result is not coming as expected.我正在尝试使用
Javascript
将一个 object 数组转换为一个嵌套的 object 结构,但结果没有达到预期。 I am explaining my code below.我在下面解释我的代码。
let data = [
{
"hop_no": 1,
"jumphost_id": "jumphost1"
},
{
"hop_no": 2,
"jumphost_id": "jumphost2"
},
{
"hop_no": 3,
"jumphost_id": "another-jumphost"
},
{
"hop_no": 4,
"jumphost_id": "last-jumphost"
}
]
let result ='';
for(let i = 0; i< data.length; i++) {
const index = i+1;
const obj = data.find(o => o.name === index);
if(result === '' && !result['host-id']) {
result = {
"host-id": obj.jumphost_id,
"next-hop":{}
}
}else{
if(result['next-hop'] === '') {
result['next-hop'] = obj.jumphost_id
}
}
}
Here the array of object is given ie- data
and my expected structure is given below.这里给出了 object 的数组
ie- data
,下面给出了我预期的结构。
Expected result below.预期结果如下。
{
"host-id": "jumphost1",
"next-hop": {
"host-id": "jumphost2",
"next-hop": {
"host-id": "another-jumphost",
"next-hop": {
"host-id": "last-jumphost",
}
}
}
}
Here the condition is when "hop_no": 1
the respective jumphost_id
value will assign to host-id
and will be the first key.这里的条件是当
"hop_no": 1
相应的jumphost_id
值将分配给host-id
并且将是第一个键。 after that the nested object structure will be formed in ascending order of hop_no
value and the respective jumphost_id
value will assign to next-hop
key.之后嵌套object结构将按照
hop_no
值的升序排列,并将各自的jumphost_id
值分配给next-hop
密钥。 Can anybody help me to design this structure using Javascript only.谁能帮我设计这个结构,只使用 Javascript。
You can do this with a reduce
function:您可以使用
reduce
function 来执行此操作:
let data = [{ "hop_no": 1, "jumphost_id": "jumphost1", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 2, "jumphost_id": "jumphost2", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 3, "jumphost_id": "another-jumphost", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 4, "jumphost_id": "last-jumphost", ip: "", port: 22, user: "", password: "", "device-type": "linux" } ] let result = data.sort((a, b) => b.hop_no - a.hop_no).reduce((prev, curr, i, array) => { let { hop_no, jumphost_id, ...rest } = curr return { 'host-id': jumphost_id, ...rest, ...(i > 0? {'next-hop': {...prev }}: {}), } }, {}) console.log(result)
You can try to build the object from inside out.您可以尝试从内到外构建 object。
Like so:像这样:
let data = [ { "hop_no": 1, "jumphost_id": "jumphost1" }, { "hop_no": 2, "jumphost_id": "jumphost2" }, { "hop_no": 3, "jumphost_id": "another-jumphost" }, { "hop_no": 4, "jumphost_id": "last-jumphost" } ] let result = {}; for (var i = data.length - 1; i >= 0; i--) { let tmp = { 'host-id': data[i]['jumphost_id'], }; if (Object.keys(result).length;== 0) { tmp['next-hop'] = result; } result = tmp. } console;log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.