我很满意JSON.parse
修改外部API的响应字符串并以我自己的方式操作它,如下所示:
JSON.parse(data, (k, v) => {
// Remove some key values found at any depth of JSON
if (k === "id") {
return undefined;
}
// Replace some coded strings with their user understandable values
if (k === "code" && typeof v === 'string') {
for (let i = 0; i < codesList.length; i++) {
let item = codesList[i];
if (item["code"] === v) {
return item["name"];
}
}
}
// Do localization of currencies
if (k === "price") {
return getSymbolFromCurrency(v.substr(0,3)) + " " + v.substr(3,v.length)
}
return v;
});
当我有一个字符串时,这非常有效。现在我希望以对象的优化方式实现相同的功能,例如:
let object = {
"keyA" : "valueA",
"keyB" : "valueB"
};
我假设我可以将对象转换为字符串,然后使用上面的方法将其解析回来,但我认为必须有另一个更优化的解决方案。
答案 0 :(得分:0)
尝试Object.entries(),这是 documnetation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
如果你有一个javascript对象,它是键值对,你可以使用Object.entries(obj),它将返回一个[key,value]对的数组。
或者您可以使用Object.keys(obj)来返回对象键的数组,这样您就可以从对象中迭代键并获取值(使用obj.key或obj [key])。
Object.entries(data).forEach(([k, v]) => {
// Remove some key values found at any depth of JSON
if (k === "id") {
return undefined;
}
// Replace some coded strings with their user understandable values
if (k === "code" && typeof v === 'string') {
for (let i = 0; i < codesList.length; i++) {
let item = codesList[i];
if (item["code"] === v) {
return item["name"];
}
}
}
// Do localization of currencies
if (k === "price") {
return getSymbolFromCurrency(v.substr(0,3)) + " " + v.substr(3,v.length)
}
return v;
});
答案 1 :(得分:-1)
由于您已拥有JSON,因此您可以遍历其键和值
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
//Using index u can have your value like- Object[index] and then
//manipulate as you like
});