【问题标题】:Filtering an Object in Array with javascript in react native在本机反应中使用javascript过滤数组中的对象
【发布时间】:2019-03-05 08:30:41
【问题描述】:

我被困在一些我认为很愚蠢的事情上,但是在尝试了一些东西之后,我找不到解决方案。有什么建议吗?

我有一个包含这种格式的对象的数组:

   [
    Object {
      "name": "name",
     "description": "100 jours ferme",
     "image: "path_image",
     "culture": Array [
      Object {
        "name": "name",
        "value": "309",
      }
    ]}
    ...
    ]

在我的react native 项目中使用一个函数,我得到一个selected value,例如:309

所以我要做的是创建一个New Array,其中在culture 内的我的对象中只包含包含此值的项目,并修改我的数组的状态(使用setState)

我知道我可以用.map() 映射所有culture 数组,但后来我被卡住了。 我只想说“我想要一个包含这些元素的新数组”......

然后,我知道我是否有类似的东西:

"culture": 309

我本来可以这样做的:myArray.filter(i => i.culture == selectedValue)

任何关于我如何使用.filter(), .map() 做到这一点的帮助?

谢谢

【问题讨论】:

标签: javascript arrays reactjs object filter


【解决方案1】:

您可以在数组上使用Array.prototype.filter,然后为每个culture 运行Array.prototype.find,谓词为

o => o.value === selectedValue

这是一个运行示例:

const arr = [
  {
    name: "name",
    description: "100 jours ferme",
    image: "path_image",
    culture: [{
      name: "name",
      value: "309"
    }]
  },
  {
    name: "name",
    description: "100 jours ferme",
    image: "path_image",
    culture: [{
      name: "name",
      value: "308"
    }]
	}
];

const selectedValue = '309';
const newArr = arr.filter(obj => obj.culture.find(o => o.value === selectedValue));
console.log(newArr)
.as-console-wrapper { max-height: 100% !important; }

【讨论】:

  • 我有一个错误尝试:undefined is not an object (evaluating 'obj.culture.find')...有什么想法吗?
  • 好像你得到了 undefined 而不是一个对象。如果没有minimal reproducible example,我真的无法知道
  • 您的示例运行正常。如果我以静态方式复制通过API 收到的数据,它也可以工作......但我只是尝试过滤/查找我通过API 得到的数据,并且我处于我的状态。它不是。有关信息,我正在通过React Navigation 的参数传递我的数据(静态数据有效,来自 API 编号的那个)然后让您知道我收到了这种格式的对象:{{info},{ info}} 我把它改成这样: Object.values(response.data) 也许有一些线索:-)
  • 您应该在问题中包含您正在使用的代码
【解决方案2】:

用特定键过滤数组,

var filterArray = detailArray.filter(
      data => data.service === serviceIdentifier,
    );

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2020-08-27
    相关资源
    最近更新 更多