javascript - 将值映射到对象数组中

标签 javascript arrays ecmascript-6 array-map

我有一个数组

const nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
};

我想保留数组,但所有图层值都应该更改。

输入层的值应为 1,所有数值应增加 2,输出层应具有新的最高数值加 1。所有值都应为数字而不是字符串。

所以新的数组将是

const nodes = [
    { layer: 2 },
    { layer: 1 },
    { layer: 2 },
    { layer: 4 },
    { layer: 3 }
};

我已经完成了这个

const nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
};

const output = Math.max.apply(Math, nodes.map((node) => Number.parseInt(node.layer, 10) || 0)) + 3;

nodes.map((node) => {
  layer: neuron.layer === 'input' ? 1 : (neuron.layer === 'output' ? output : Number.parseInt(neuron.layer, 10) + 2)
})

看起来可行,但是代码真的很难看。

我想知道是否可以做得比这更简洁。

最佳答案

这个怎么样:

const nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
];

nodes.filter( o => o.layer === 'output' )[0].layer = 
    1 + nodes.reduce( (max, node) => Math.max(max, 
        node.layer = +(node.layer === 'input') || +node.layer+2 || 0), 0);

console.log(nodes);

对于那些想了解 const 的人:常量性质仅保护变量免于重新分配;但存储在数组中的对象可以自由改变。

关于javascript - 将值映射到对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38860037/

相关文章:

javascript - Angular typescript : Swagger CodeGen Generator making all class properties Nullable

ios - 无法将类型 'Option' 的值转换为预期的参数类型 '@noescape (Option) throws -> Bool'

java - 将数字放入数组

javascript - ECMAScript 6 在对象解构中扩展了语法。支持 TypeScript 和 Babel

javascript - 在 js 类中,调用 super 将所有参数传递给父类的更好方法是什么?

javascript - 在单页应用程序中上传文件

javascript - AngularJS 路由到路径而不是加载 html 页面

javascript - Rxjs : prevent pushing data to subjects from outisde the service

javascript - Express.js - 使用嵌套请求从备份 URL 获取 JSON

c - 数组到 C 中的链表函数;如何遍历列表以附加节点?