避免通过遍历JSON对象获取数组索引

时间:2019-07-03 07:12:10

标签: javascript angular lodash

方法:-

const getAllKeys = obj => _.union(
  _.keys(obj),
  _.flatMap(obj, o => _.isObject(o) ? getAllKeys(o) : [])
)

示例JSON:-

const arr = {"{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}}

const result = getAllKeys(arr)
console.log(result);

结果:-

["0", "1", "name", "url"]

在结果集中的何处,我需要避免获取"0""1"的数组索引,有关如何使其成为可能的任何想法?我只需要不带数组索引的唯一键。

语言:Angular 4 + lodash + javascript

1 个答案:

答案 0 :(得分:2)

使用_.keys()

const arr = [{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}]

const getAllKeys = obj => _.uniq(
  _.flatMap(obj, o => _.isObject(o) ? _.keys(o) : [])
)

console.log(getAllKeys(arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>