下面是我的示例数据
const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}, {"amount": "300,000", "cover": null, "id": "2", "img": "63723574a81ce.1.png", "make": "ferrari", "model": "ferrari", "name": "CIC", "policy": "Motor Insurance", "rate": "3"}, {"amount": "450,000", "cover": null, "id": "3", "img": "63723726cb1df.1.png", "make": "audi", "model": "audi", "name": "Mayfair Insurance", "policy": "Motor Insurance", "rate": "4.5"}]
这是am用来返回id3的数组的代码。
const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}, {"amount": "300,000", "cover": null, "id": "2", "img": "63723574a81ce.1.png", "make": "ferrari", "model": "ferrari", "name": "CIC", "policy": "Motor Insurance", "rate": "3"}, {"amount": "450,000", "cover": null, "id": "3", "img": "63723726cb1df.1.png", "make": "audi", "model": "audi", "name": "Mayfair Insurance", "policy": "Motor Insurance", "rate": "4.5"}]
const id = ['3']
const provider = data.reduce((prv, item) => {
if(id.includes(item.id)){
return prv
}
return prv
});
console.log('This is provider' ,provider);
不幸的是,我得到的返回是id为1的数据
输出量:
This is provider {"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}
有人能告诉我哪里做错了吗
3条答案
按热度按时间vvppvyoh1#
如果你的目的是只返回一个对象,你可以使用
reduce()
,但目前,你用的方法有点错误。1.你需要传递一个初始值给
reduce()
,如果不是,那么reduce
会选择数组的第一个元素作为初始值,并从第二个元素开始迭代。所以当条件为假时,它会返回数组的第一个元素。所以你需要小心使用它。1.您需要在此处返回
item
,而不是prev
。以下是
.reduce()
的解决方案您也可以使用
.filter()
t3irkdon2#
To return a single array of data from a given set of data in React Native, you can use the
Array.prototype.concat()
method to combine the individual arrays into a single array. For example, if you have the following data:You can use the concat() method to combine the arrays into a single array, like this:
This will return the following array:
Alternatively, you can use the
Array.prototype.flat()
method, which was introduced in ECMAScript 2019 and is supported by React Native. This method allows you to flatten an array of arrays into a single array, like this:This will also return the following array:
bvuwiixz3#
看起来您的代码无法正常工作,因为您错误地使用了Array.reduce()方法。reduce()方法用于将数组缩减为单个值,而不是过滤掉数组中的值。
要过滤掉id为3的数据,可以使用Array.filter()方法。下面是使用filter()方法时的代码:
这将输出以下数据: