gpt4 book ai didi

javascript - javascript/jquery 中的对象问题

转载 作者:行者123 更新时间:2023-11-29 17:51:51 25 4
gpt4 key购买 nike

var node = {
node: {
name: "someone1",
city: "somewhere1",
state: "someplace1"
},
node : {
name: "someone2",
city: "somewhere2",
state: "someplace2"
},
node : {
name: "someone3",
city: "somewhere3",
state: "someplace3"
}
};


console.log(JSON.stringify(node.node));
//Output is {"name":"someone3","city":"somewhere3","state":"someplace3"}

但我需要完整的数据,比如当我输入 node.name 时......所有名称都应该显示

最佳答案

你不应该让对象具有同名的属性,对象中的键应该保持唯一。你可以有一个数组并循环遍历它

var node = [
{
name: "someone1",
city: "somewhere1",
state: "someplace1"
},{
name: "someone2",
city: "somewhere2",
state: "someplace2"
}, {
name: "someone3",
city: "somewhere3",
state: "someplace3"
}
]

node.forEach(function(item){
console.log(item.name);
})

更新:考虑到您在评论中指出的嵌套对象,将值设置为输入。

您需要递归才能找到嵌套对象中的所有名称

$(function(){
var node = {
"id": "429428",
"name": "something",
"state": {
"filter": "98887"
},
"node": {
"id": "49888",
"name": "something2",
"state": {
"filter": "48765"
},
"node": {
"id": "428866",
"name": "something3",
"state": {
"filter": "998898"
}
}
}
}
var arr = [];
function getValues(node, arr) {
for (prop in node) {
console.log(prop);
if(prop == "name") {
arr.push(node[prop]);

}
if(prop == "node") {
getValues(node[prop], arr)
}
}
}

getValues(node, arr)




console.log(arr.join(" "));

document.getElementById('ip').value = arr.join(" ");
})
<input type="text" id="ip"/>

关于javascript - javascript/jquery 中的对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42835754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com