繁体   English   中英

JSON.parse用于JSON对象而不是字符串

[英]JSON.parse for JSON object instead of a string

我对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"
    };

我假设可以将对象转换为字符串,然后使用上述方法将其解析回去,但是我认为必须对此有另一个更优化的解决方案。

尝试使用Object.entries(),这里是文档https://developer.mozilla.org/zh-CN/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;
});

由于已经有了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
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM