javascript中字符串数组获取对象所有叶节点属性的函数
A function to obtain all leaf node properties of an object in an array of string in javascript
请求您帮助在 javascript 中构建一个函数,以从给定的输入中获得提到的输出。
INPUT : 一个对象(可能是嵌套对象)
示例:
{
"消息":"字符串",
“数据 1”:{
"Output1": {
"leaf1": "abc",
"Leaf2": "123"
}
}
“数据2”:{
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
输出:字符串数组
示例:
str= ["消息", "data1.Output1.leaf1", "data1.Output1.leaf2", "data2.Output2.leaf3","data2.Output2.leaf4"]
像这样它会起作用
const getBranches = (data, prefix=[]) => {
if (typeof(data) !== 'object') {
return prefix.join('.')
}
return Object.entries(data).flatMap(([k, v]) => getBranches(v, [...prefix, k]))
}
const data = {
"message": "string",
"data1": {
"Output1": {
"leaf1": "abc",
"Leaf2": "123"
}
},
"data2": {
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
console.log(getBranches(data))
第二个版本
const data = {
"message": "string",
"data1": {
"Output1": {
"leaf1": [{
"b": {
"c": "12"
}
}]
}
},
"data2": {
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
const getBranches = (data, prefix = []) => {
if (typeof(data) !== 'object') {
return prefix.join('.')
}
return Object.entries(data).flatMap(([k, v]) => Array.isArray(data) ? getBranches(v, [...prefix]) : getBranches(v, [...prefix, k]))
}
console.log(getBranches(data))
请求您帮助在 javascript 中构建一个函数,以从给定的输入中获得提到的输出。
INPUT : 一个对象(可能是嵌套对象)
示例:
{
"消息":"字符串",
“数据 1”:{
"Output1": {
"leaf1": "abc",
"Leaf2": "123"
}
}
“数据2”:{
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
输出:字符串数组
示例: str= ["消息", "data1.Output1.leaf1", "data1.Output1.leaf2", "data2.Output2.leaf3","data2.Output2.leaf4"]
像这样它会起作用
const getBranches = (data, prefix=[]) => {
if (typeof(data) !== 'object') {
return prefix.join('.')
}
return Object.entries(data).flatMap(([k, v]) => getBranches(v, [...prefix, k]))
}
const data = {
"message": "string",
"data1": {
"Output1": {
"leaf1": "abc",
"Leaf2": "123"
}
},
"data2": {
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
console.log(getBranches(data))
第二个版本
const data = {
"message": "string",
"data1": {
"Output1": {
"leaf1": [{
"b": {
"c": "12"
}
}]
}
},
"data2": {
"Output2": {
"leaf3": "abc",
"leaf4": "123"
}
}
}
const getBranches = (data, prefix = []) => {
if (typeof(data) !== 'object') {
return prefix.join('.')
}
return Object.entries(data).flatMap(([k, v]) => Array.isArray(data) ? getBranches(v, [...prefix]) : getBranches(v, [...prefix, k]))
}
console.log(getBranches(data))