gpt4 book ai didi

Javascript - 将元素添加到具有固定值的查询结果的最佳/最快方法

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:24 25 4
gpt4 key购买 nike

我有一个 node.js mysql 查询:

connection.query("SELECT id AS id, name AS label, status AS status from table;", function(err, rows) {
...
});

我得到的锁是这样的:

控制台日志(getBody)

[ { id: '1',
label: 'Name 01',
status: 'ACTIVE' },
{ id: '2',
label: 'Name 02',
status: 'INACTIVE' },
{ id: '3',
label: 'Name 03',
status: 'ACTIVE' },
{ id: '4',
label: 'Name 04',
status: 'ACTIVE' }];

要进一步使用结果...我需要一个额外的参数“类型”,在数组中有一个固定值。所以结果应该是这样的:

[ { id: '1',
label: 'Name 01',
status: 'ACTIVE',
type: 'ABC' },
{ id: '2',
label: 'Name 02',
status: 'INACTIVE',
type: 'ABC' },
{ id: '3',
label: 'Name 03',
status: 'ACTIVE',
type: 'ABC' },
{ id: '4',
label: 'Name 04',
status: 'ACTIVE',
type: 'ABC' }];

最快/最好的方法是什么?遍历数组?它应该是什么样子?

最佳答案

使用 map方法:

const newArray = array1.map(element => element = {...element, ...{type: 'ABC'}});
console.log(array1); // array1 won't be changed
console.log(newArray);

forEach ,这将修改您的数组:

array1.forEach(element => element.type = 'ABC');
console.log(array1);

关于Javascript - 将元素添加到具有固定值的查询结果的最佳/最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com