我想使用不同的键循环遍历数组中的对象,而不使用for-each循环:
[ { id: 1,
ip: 'xx.xxx.xx.xx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: '' },
{ id: 2,
ip: 'xxx.xxx.xx.xx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: '' },
{ id: 4,
ip: 'xxx.xxx.xx.xxx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: '' } ]
我想检查每列mn的长度值,然后用一些信息对其进行更新,如果有其他条件,我可以这样做,但是我认为这样做有更好的方法。我尝试使用Object.entries
然后进行for循环,但是由于id和ip列而无法使用。
答案 0 :(得分:2)
也许这样的东西对您有用吗?此解决方案采用实用的方法来解决您的问题,并避免显式使用for-loop
构造:
var input = [ { id: 1,
ip: 'xx.xxx.xx.xx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: '' },
{ id: 2,
ip: 'xxx.xxx.xx.xx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: '' },
{ id: 4,
ip: 'xxx.xxx.xx.xxx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: '' } ];
var output = input.map(object => {
return Object.entries(object).reduce((result, entry) => {
let key = entry[0];
let value = entry[1];
if(key.startsWith('mn')) {
value = `updated value for ${ key }`;
}
result[key] = value;
return result;
}, {});
});
console.log(output);
答案 1 :(得分:1)
您可以在修改密钥之前检查其名称。
这有帮助吗?通过运行代码片段进行尝试。
const arr = [{
id: 1,
ip: 'xx.xxx.xx.xx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: ''
},
{
id: 2,
ip: 'xxx.xxx.xx.xx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: ''
},
{
id: 4,
ip: 'xxx.xxx.xx.xxx',
mn1: '',
mn2: '',
mn3: '',
mn4: '',
mn5: '',
mn6: '',
mn7: ''
}
];
console.log('BEFORE', JSON.stringify(arr, null, 2));
for (const item of arr) {
for (const key of Object.keys(item)) {
if (!key.startsWith('mn')) continue;
// know if the code gets here then it's an `mn` key
// you can do logic here on the key
// and then manipulate the result
item[key] = 'changed';
}
}
console.log('AFTER', arr);
答案 2 :(得分:1)
您可以使用Object.entries
,Array.prototype.filter
和Array.prototype.forEach
来发挥自己的优势。
const transform = value => `transformed-${value}`;
const arr = [{ id: "id", ip: "ip", otherKey: "other" }];
arr.forEach(obj => {
Object.entries(obj)
.filter(([key]) => key !== "id" && key !== "ip")
.forEach(([key, value]) => (obj[key] = transform(value)));
});
console.log(arr)
但是,如果您不能使用最新的ECMAScript功能,则会开始变得冗长:
var transform = function(value) { return "transformed-" + value };
var arr = [{ id: "id", ip: "ip", otherKey: "other" }];
arr.forEach(function(obj) {
Object.entries(obj)
.filter(function(keyValue) {
var key = keyValue[0];
return key !== "id" && key !== "ip";
})
.forEach(function(keyValue) {
var key = keyValue[0],
value = keyValue[1];
obj[key] = transform(value);
});
});
console.log(arr)
如果您被困在没有Babel的项目中,那么最好的选择可能是您最初的建议。
var transform = function(value) { return "transformed-" + value };
var arr = [{ id: "id", ip: "ip", otherKey: "other" }];
arr.forEach(function(obj) {
Object.entries(obj).forEach(function(keyValue) {
var key = keyValue[0],
value = keyValue[1];
if (key !== "id" && key !== "ip") {
obj[key] = transform(value);
}
});
});
console.log(arr)