我正在遍历一个嵌套对象。返回数据由两个数组包装。我明白为什么会这样,但我不明白如何取回所需的数据。
const data = {
"foo": {
"bar": {
"id": "1",
"step": [{
"id": "33",
"copy": [{
"id": "1",
"text": "hello",
},
{
"id": "2",
"text": "whirl",
},
{
"id": "3",
"text": "whoa",
}
],
}]
}
}
}
pipe(
path(['foo', 'bar', 'step']),
map(step =>
step.copy.map(s => ({text: s.text}))
)
) (data)
返回数据返回这个:
[[{"text": "hello"}, {"text": "whirl"}, {"text": "whoa"}]]
我想返回:
[{"text": "hello"}, {"text": "whirl"}, {"text": "whoa"}]
最佳答案
问题是 step
本身就是一个 array
。您需要获取它的第一项或在参数中传递 0
。这里是一个纯js版本的从路径中查找数据。我使用了reduce()
const data = { "foo": { "bar": { "id": "1", "step": [{ "id": "33", "copy": [{ "id": "1", "text": "hello" }, { "id": "2", "text": "whirl" }, { "id": "3", "text": "whoa" } ] }] } } }
function getFromPath(obj, path) {
return path.reduce((ac, a) => ac[a] || {}, obj);
}
let res = getFromPath(data, ["foo","bar","step",0,"copy"]).map(({text}) => ({text}))
console.log(res)
关于javascript - 如何删除外部阵列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348738/