javascript - 如何删除外部阵列?

标签 javascript arrays ramda.js

我正在遍历一个嵌套对象。返回数据由两个数组包装。我明白为什么会这样,但我不明白如何取回所需的数据。

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/

相关文章:

javascript - 在 setTimeout 内更新状态(React 和 React-Native)

c# - index 和 count 必须引用缓冲区中的位置。参数名称字节

javascript - Ramda 两者都否定

javascript - 在 Typescript 中使用 Ramda Pipe 输入错误

javascript - Ramda 找到两个不同的嵌套键值

javascript - IE6 中的 "Member not found"错误 : from . 样式编辑或 getElementById 或...?

javascript - 如何使 Angular $filter 过滤区分大小写的字符串比较器

javascript - Uncaught ReferenceError : loadImage is not defined

java - 从方法返回数组

为二维数组调用 Array.GetLength(1) 时出现 C# IndexOutOfRangeException