【发布时间】:2022-01-13 07:03:30
【问题描述】:
我有一个过滤数组的简单函数。
我只想要字符串值,而不是整个对象。
为什么返回的是整个对象而不仅仅是字符串?
如果我将返回切换到 console.log(),我会得到所需的输出
有什么想法吗?
这里是代码
const Array2 = [
{ header: 'First name', HeaderIndex: 0},
{ header: 'Last name', HeaderIndex: 1},
{ header: 'Company', HeaderIndex: 2},
{ header: 'Favorite food', HeaderIndex: 3},
{ header: 'Favorite color', HeaderIndex: 4},
]
const testing = Array2.filter((obj) => { if(obj.HeaderIndex === 1) { return obj.header } } )
console.log(testing)
// gives undesired output
[{…}]
0: {header: 'Last name', HeaderIndex: 1}
length: 1
[[Prototype]]: Array(0)
const testing = Array2.filter((obj) => { if(obj.HeaderIndex === 1) { console.log(obj.header)} } )
// gives desired output
"Last name"
我有问题的输出如下,我只想返回字符串
[{…}]
0: {header: 'Last name', HeaderIndex: 1}
length: 1
[[Prototype]]: Array(0)
更新*
我接受了 Mayur 的回答,因为它在更大的用例中解决了我的问题。下面是我更大的用例,我需要根据需要匹配 Array2 中的 HeaderIndex 的 Array1 索引来合并这两个数组
const Array1 = [
['Alex', 'Boe', 'MeowWolf', 'pizza', 'pink'],
['Arron', 'Coe', 'Kmart', 'tofu', 'purple'],
['Jane', 'Doe', 'Sears', 'tacos', 'orange'],
['John', 'Eoe', 'YugiOh', 'blueberries', 'magenta'],
['Suzie', 'Boe', 'Toyota', 'steroids', 'blue']
]
const Array2 = [
{ header: 'First name', HeaderIndex: 0},
{ header: 'Last name', HeaderIndex: 1},
{ header: 'Company', HeaderIndex: 2},
{ header: 'Favorite food', HeaderIndex: 3},
{ header: 'Favorite color', HeaderIndex: 4},
]
const testResult = Array1.map((arr) => arr.map((string) => { return {"ChosenHeader": Array2.filter((obj) => obj.HeaderIndex === arr.indexOf(string))[0]?.header, "content": string}} ))
console.log(testResult)
// desired output
[
0: {ChosenHeader: 'First name', content: 'Alex'}
1: {ChosenHeader: 'Last name', content: 'Boe'}
2: {ChosenHeader: 'Company', content: 'MeowWolf'}
3: {ChosenHeader: 'Favorite food', content: 'pizza'}
4: {ChosenHeader: 'Favorite color', content: 'pink'}
]
【问题讨论】:
-
.filter()仅包含或排除项目。它接受一个数组并返回 less。不会改变结果。你给它的回调是一个谓词——它只需要为包含或排除的内容产生真假。 -
过滤器不是这样工作的。它只是选择哪些数组元素将出现在结果中,它不会更改元素。您可以在过滤之前或之后使用
map() -
其实你最好这样使用
find:const { header } = Array2.find((obj) => obj.HeaderIndex === 1)然后console.log(header) -
这是亚历山大的好答案
标签: javascript arrays