如何循环遍历JavaScript对象中的所有成员,包括作为对象的值?
例如,我如何循环(分别访问“your_name”和“your_message”)?
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
每个2
(在此处找到):
var lunch = {
sandwich: 'ham',
age: 48,
};
lunch.forEach2(function (item, key) {
console.log(key);
console.log(item);
});
代码:
if (!Object.prototype.forEach2) {
Object.defineProperty(Object.prototype, 'forEach2', {
value: function (callback, thisArg) {
if (this == null) {
throw new TypeError('Not an object');
}
thisArg = thisArg || window;
for (var key in this) {
if (this.hasOwnProperty(key)) {
callback.call(thisArg, this[key], key, this);
}
}
}
});
}
2020年,您需要不可变的通用函数
这将遍历由子对象、数组和字符串组成的多维对象,并应用自定义函数:
export const iterate = (object, func) => {
const entries = Object.entries(object).map(([key, value]) =>
Array.isArray(value)
? [key, value.map(e => iterate(e, func))]
: typeof value === 'object'
? [key, iterate(value, func)]
: [key, func(value)]
);
return Object.fromEntries(entries);
};
用法:
const r = iterate(data, e=>'converted_'+e);
console.log(r);