我正在使用 .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 看起来并不适合您的用例。我建议使用“ map ”方法。 例如,
如果有数组,
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 } ]
关于javascript - 使用函数内检索和更新的数据更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905274/