首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将此对象数组转换为使用reduce javascript

如何将此对象数组转换为使用reduce javascript
EN

Stack Overflow用户
提问于 2019-02-10 12:18:10
回答 5查看 112关注 0票数 0

我正在尝试将此函数转换为使用reduce。我已经完成了一半。当选择的值为true时,我想知道该元素的索引。

代码语言:javascript
运行
复制
let options = [
    {label: 'foo1', selected: false},
    {label: 'foo2', selected: true},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
];
const obj = options
              .map((option, index) => (option.selected ? index : -1))
              .filter((val) => val !== -1)[0];

结果:1

我的尝试是这样的:

代码语言:javascript
运行
复制
const obj = options.reduce((acc, currentValue, index) => {
    const i = currentValue["selected"] ? index : -1;
    return acc.concat(i)
}, []); // [-1,1,-1,-1,-1]

如何将整个内容更改为使用reduce?

EN

回答 5

Stack Overflow用户

发布于 2019-02-10 12:23:33

仅当option.selected为true时才将索引添加到结果中,否则不执行任何操作。

代码语言:javascript
运行
复制
let options = [
    {label: 'foo1', selected: false},
    {label: 'foo2', selected: true},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
];

const selected = options.reduce((arr, option, index) => {
  return option.selected ? arr.concat(index) : arr; 
}, []);

console.log(selected);

票数 1
EN

Stack Overflow用户

发布于 2019-02-10 12:25:24

concat()中使用三元值来设置要插入的值。Array#concat()返回更新后的数组,这就是reduce()的返回值。

或者使用spread返回新的数组[...accumulator, selsected ? i :-1]

代码语言:javascript
运行
复制
const res = options.reduce((a, {selected:s}, i) =>  a.concat(s ? i : -1) , []);

// OR
// const res = options.reduce((a, {selected:s}, i) =>  [....a,s ? i : -1] , []);

console.log(res)
代码语言:javascript
运行
复制
<script>

let options = [
    {label: 'foo1', selected: false},
    {label: 'foo2', selected: true},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
];

</script>

票数 1
EN

Stack Overflow用户

发布于 2019-02-10 12:23:11

如果您想要selected = true的索引,那么可以使用reduce来做类似这样的事情。如果上下文中的当前项具有selected === true,则将索引添加到累加器,否则返回累加器。当前,如果条件为false,则添加-1

代码语言:javascript
运行
复制
let options = [
    {label: 'foo1', selected: false},
    {label: 'foo2', selected: true},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
    {label: 'foo2', selected: false},
];

const selectedIndexes = options.reduce((r, o, i) => o.selected ? r.concat(i) : r, [])
console.log(selectedIndexes)

如果您想要整个对象,那么您可以简单地使用filter

代码语言:javascript
运行
复制
let options = [{label:'foo1',selected:false},{label:'foo2',selected:true},{label:'foo2',selected:false},{label:'foo2',selected:false},{label:'foo2',selected:false},];

const filtered = options.filter(o => o.selected)
console.log(filtered)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54613300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档