假设我有以下对象。
{
...
a: 12,
...
}
第二个对象。
{
...
subOjb: {
a: 53
},
...
}
第三个对象。
{
...
subOjb: {
subSub: {
a: 32
}
},
...
}
假设我有兴趣寻找属性a
的值,而不管其嵌套的深度如何。不管嵌套的深度如何,是否都有一个图书馆来获取财产的价值。
答案 0 :(得分:6)
一种选择是利用JSON.stringify
,它将对所有属性进行递归迭代,而无需使用库:
const obj = {
foo: 'foo',
outer: [
'item',
{
inner: {
prop: 'prop',
another: {
a: 'theValueOfA'
}
}
}
]
};
let a;
JSON.stringify(obj, (key, val) => {
if (key === 'a') a = val;
return val;
});
console.log(a);
另一种选择,编写自己的递归函数,该函数在对象的entries
上进行迭代:
const obj = {
foo: 'foo',
outer: [
'item',
{
inner: {
prop: 'prop',
another: {
a: 'theValueOfA'
}
}
}
]
};
const findProp = (obj, prop) => Object.entries(obj).reduce((a, [key, val]) => {
if (a) return a;
if (key === prop) return val;
if (typeof val === 'object') return findProp(val, prop);
}, null);
console.log(findProp(obj, 'a'));
答案 1 :(得分:1)
我假设您正在寻找 It has been solved.js has been modified.
That is, the parameters carried by the URL through the Ajax request to the
back-end again, and then the back-end returned JSON data inserted into the
specified location again, probably this is the solution, my English is not
very good, please forgive me.
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
fun();
});
function fun() {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
});
}
function pagedata(){
$(".page-item a").click(function (){
var href=this.href;
this.href="javascript:void(0);";
var id=getQueryVariable('page',href);
var key=getQueryVariable('key',href);
var page=getQueryVariable('page',href);
$.ajax({
type: "get",
url: "accept",
dataType: 'json',
data: {id: id, key: key,page:page},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
})
})
}
// Intercept the parameter values carried by URL, such as page parameters
//and some custom parameters.
function getQueryVariable(name,url) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var data=url.slice(url.indexOf('?'));
var r =data.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
</script>
的首次出现。在这种情况下,您基本上想进行广度优先搜索(Wikipedia article on BFS)。
a