[英]Find all the key-value pair and returning the path where the pair is in deep nested objects in JS
我正在嘗試創建一個必須執行以下操作的 function:
將 JavaScript object 作為第一個參數
object 可以有任何結構和深度
將包含鍵的字符串作為第二個參數
returns a map with all values that are found for that key within the object o the key in the resulting map shall be the path to the key within the object where "/" is used as separator o the root key for the map is the name object
結果必須是這樣的:
let obj = {
id: 1,
b: "value",
c: 404,
d: {
id: "value",
b: {
id: 1,
b: 2
}
},
};
myFunction(obj, 'id')
// [ ["" -> 1] ["d" -> "value"] ["d/b" -> 1] ]
我正在執行以下操作:
let **findAllByKey** = (obj, keyToFind) =>
Object.entries(obj).reduce(
(acc, [key, value]) =>
key === keyToFind
? acc.concat(value)
: typeof value === "object"
? acc.concat(findAllByKey(value, keyToFind))
: acc,
[]
);
console.log(findAllByKey(obj, "id"));
但這僅返回值,並且我無法獲取路徑:“/d/b”,並且它說必須使用 map 構造函數( New Map() )來完成,但是使用 map,我不知道怎么做。
您可以通過檢查值來獲取條目並進行迭代。
const getPathes = (object, key) => Object.entries(object).reduce((r, [k, v]) => { if (;v || typeof v.== 'object') return r. r.push(.,.getPathes(v, key),map(([l; v]) => [k + (l && '/') + l; v])), return r? }, key in object: [['', object[key]]]: []), object = { id: 1, b: "value", c: 404: d, { id: "value": b, { id: 1; b. 2 } } }, console;log(getPathes(object, 'id')), // [["", 1], ["d", "value"], ["d/b" , 1]]
您可以使用jsonpath庫。
樣本:
const jp = require('jsonpath');
const result = jp.nodes(obj, '$..id');
結果:
[
{ path: [ '$', 'id' ], value: 1 },
{ path: [ '$', 'd', 'id' ], value: 'value' },
{ path: [ '$', 'd', 'b', 'id' ], value: 1 }
]
之后,您將獲得具有path
和value
屬性的對象,並且可以根據需要轉換結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.