javascript - 使用在函数内部检索和更新的数据更新数组
问题描述
我正在使用 .reduce 函数从数组中获取数据,我不确定这是否是最好的方法,但是由于我在另一篇文章中获得的一些帮助,这是目前唯一可行的方法。
我不知道如何使用函数中所做的更改来更新数组,返回数组忽略所做的更改。
数据由路由器提供并每秒更新一次。
var data = [
{ macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: '1.1.1.1',
tx: '0',
rx: '384'},
{ macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: '8.8.8.8',
tx: '384',
rx: '384'},
{ macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: '1.1.1.1',
tx: '384',
rx: '384',},
];
// We resolve the DNS and output the final array
let DNSvariable = result.reduce((arr, currentValue) => {
var setIP = currentValue.dstAddress;
var dns = require('dns');
dns.setServers([
'8.8.8.8',
]);
// Test that IP's are being received correctly.
console.log(setIP);
// Resolve the IP addresses
dns.reverse(setIP, (err, address) => {
currentValue.dstAddress = address;
// If I log the currentValue inside this function everything looks correct, it has updated the values in the full array. I need to push this array, into the returned array.
});
return arr;
}, []);
// Logging the variable produces the array with the original IP
console.log(DNSvariable);
我想要 console.log(DNSvariable); 返回具有解析名称的数组,此时它正在返回地址。我只是不知道如何更新数组。
预期结果将是:
var data = [
{ macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'one.one.one.one',
tx: '0',
rx: '384'},
{ macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'dns.google',
tx: '384',
rx: '384'},
{ macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'one.one.one.one',
tx: '384',
rx: '384',},
];
如果其中任何内容不正确或发布不正确,我深表歉意。
编辑:我使用 reduce 函数的原因是因为访问 dstAddress 的所有其他方法都没有以与 dns 函数一起使用的方式返回数据。这绝对不是正确的方法。
解决方案
Reduce 看起来并不适合您的用例。我建议使用“地图”方法。例如,
如果有数组,
var arr1=[{a:1},{a:3},{a:4}]
您需要另一个包含一些修改记录的数组:
var arr2=arr1.map((elem)=>{
const elem2={...elem}
elem2.b=5;
return elem2;
})
console.log('Array1:',arr1)
console.log('Array2:',arr2)
结果:
'Array1:' [ { a: 1 }, { a: 3 }, { a: 4 } ]
'Array2:' [ { a: 1, b: 5 }, { a: 3, b: 5 }, { a: 4, b: 5 } ]
推荐阅读
- reactjs - 通用道具:为什么不能正确推断出这种类型?
- mysql - 防止并行事务期间重复的增量值
- java - 是否可以在 java 中使用数量不稳定的类进行泛型?
- python - 如何在将 TFrecords 文件提供给模型之前对其进行洗牌
- apache-spark - Spark-SQL 托管表的需求和特性
- tcp - 如果UDP是面向消息的,为什么SMTP使用TCP
- html - 鼠标悬停和鼠标单击 HTML 时发出声音
- c++ - 为什么我的平均值不能正常工作?C++
- function - 方法也是像函数一样的对象吗?
- node.js - 如何清理 Node.js 和 Typescript 中的响应正文