从多层嵌套数组JavaScript获取所有键值 [英] Get all key values from multi level nested array JavaScript

查看:52
本文介绍了从多层嵌套数组JavaScript获取所有键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象:

I have an object like this:

var data = [
	{"id":"36e1e015d703120058c92cf65e6103eb","title":"Alex McGibbon"},
	
	{"id":"60beb5e7d7600200e5982cf65e6103ad","title":"Alex Linde"},
	
	{"subs":[{"id":"62826bf03710200044e0bfc8bcbe5df1","title":"Abel Tuter"}],"id":"63e8479fdb161300bde15901cf96191c","title":"Abdul Waheed"},
	
	{"subs":[{"subs":[{"id":"12826bf03710200044e0bfc8bcbe5db1","title":"Alfonso Griglen"},{"subs":[{"id":"06826bf03710200044e0bfc8bcbe5d8a","title":"Allyson Gillispie"},{"id":"b282abf03710200044e0bfc8bcbe5d28","title":"Allan Schwantd"}],"id":"22826bf03710200044e0bfc8bcbe5dec","title":"Alejandra Prenatt"}],"id":"0a826bf03710200044e0bfc8bcbe5d7a","title":"Adela Cervantsz"},{"id":"4847c4d4d773020058c92cf65e61038e","title":"Alisa Chinoy"},{"id":"71826bf03710200044e0bfc8bcbe5d3b","title":"Aileen Mottern "},{"id":"a8f98bb0eb32010045e1a5115206fe3a","title":"Abraham Lincoln"}],"id":"7c2e6109dbd65300bde15901cf9619b5","title":"Raju Koyagura"}
	
];

console.log(data)

现在我想检索所有 id 作为新数组的值,而不考虑它是哪个嵌套级别。

Now I want to retrieve all the id values as a new array without consideration of which nested level it is.

我的预期结果是这样的::

My expected result is something like this::

var result = ['36e1e015d703120058c92cf65e6103eb','60beb5e7d7600200e5982cf65e6103ad','62826bf03710200044e0bfc8bcbe5df1','06826bf03710200044e0bfc8bcbe5d8a','b282abf03710200044e0bfc8bcbe5d28','22826bf03710200044e0bfc8bcbe5dec','0a826bf03710200044e0bfc8bcbe5d7a','4847c4d4d773020058c92cf65e61038e','71826bf03710200044e0bfc8bcbe5d3b','a8f98bb0eb32010045e1a5115206fe3a','7c2e6109dbd65300bde15901cf9619b5'];

console.log(result);

我是

推荐答案

您可以使用JSON.stringify轻松地在树上行走:

You can use JSON.stringify to walk on the tree easily:

const ids = [];
JSON.stringify(data, (key, value) => {
  if (key === 'id') ids.push(value);
  return value;
});

这篇关于从多层嵌套数组JavaScript获取所有键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆