javascript - TypeScript:将字符串转换为对象

标签 javascript node.js typescript

元字段值是一个已保存为字符串的对象 我通过 mongoose 从 mongo 获取数据

const goodsIssued = await goods
  .find({ category: username, tokenName })
  .sort([['createdAt', -1]])
  .limit(2)
  .exec();

数据看起来像..

{
    "goodsIssued": [
        {
            "minted": false,
            "_id": "5e3163597fd0ad2113bcdefe",
            "category": "gameco11",
            "goodId": 64,
            "issuedTo": "player2",
            "memo": "this is a test token",
            "meta": "{\"data\": \"text\", \"test\":1, \"works\": true}",
            "tokenName": "token5",
            "createdAt": "2020-01-29T10:50:01.257Z",
            "updatedAt": "2020-01-29T10:50:01.257Z",
            "__v": 0
        },
        {
            "minted": false,
            "_id": "5e3163587fd0ad2113bcdefd",
            "category": "gameco11",
            "goodId": 63,
            "issuedTo": "player2",
            "memo": "this is a test token",
            "meta": "{\"data\": \"text\", \"test\":1, \"works\": true}",
            "tokenName": "token5",
            "createdAt": "2020-01-29T10:50:00.691Z",
            "updatedAt": "2020-01-29T10:50:00.691Z",
            "__v": 0
        }
    ]
}

我想在将对象数组返回到前​​端之前将其转换为对象

for (const key in goodsIssued) {
  if (goodsIssued.hasOwnProperty(key)) {
    const parsedMeta = JSON.parse(goodsIssued[key].meta);
    goodsIssued[key].meta = parsedMeta;
  }
}

但它没有改变?为什么?

最佳答案

我看到两种可能性,其中任何一个都可能是问题所在,甚至可能是两者的组合。

  1. 您更新的问题显示 goodsIssued 变量被分配了一个具有 goodsIssued 属性的对象,该属性是一个数组,而您原来的问题仅显示了该数组。您的代码正在循环访问该顶级对象,而不是数组。

  2. 我怀疑您从卡住了它提供给您的完整对象树的东西中获取该对象。在这种情况下,分配给 meta 将不起作用,因为它所在的对象已被卡住。

如果我是对的,为了更新这些属性,您必须复制所有内容,也许像这样:

// 1. Get the array, not the object containing it
let goodsIssued = (await /*...get the goods*/).goodsIssued;

// 2. Create a new, unfrozen array with objects with unfrozen properties,
// and parse `meta` along the way
goodsIssued = [...goodsIssued.map(entry => ({...entry, meta: JSON.parse(entry.meta)}))];

实例:

async function getTheGoods() {
    return Object.freeze({
        "goodsIssued": Object.freeze([
            Object.freeze({
                "minted": false,
                "_id": "5e3163597fd0ad2113bcdefe",
                "category": "gameco11",
                "goodId": 64,
                "issuedTo": "player2",
                "memo": "this is a test token",
                "meta": "{\"data\": \"text\", \"test\":1, \"works\": true}",
                "tokenName": "token5",
                "createdAt": "2020-01-29T10:50:01.257Z",
                "updatedAt": "2020-01-29T10:50:01.257Z",
                "__v": 0
            }),
            Object.freeze({
                "minted": false,
                "_id": "5e3163587fd0ad2113bcdefd",
                "category": "gameco11",
                "goodId": 63,
                "issuedTo": "player2",
                "memo": "this is a test token",
                "meta": "{\"data\": \"text\", \"test\":1, \"works\": true}",
                "tokenName": "token5",
                "createdAt": "2020-01-29T10:50:00.691Z",
                "updatedAt": "2020-01-29T10:50:00.691Z",
                "__v": 0
            })
        ])
    });
}

// (Your code is apparently in an `async` function)
(async () => {
    // 1. Get the array, not the object containing it
    let goodsIssued = (await getTheGoods()).goodsIssued;

    // 2. Create a new, unfrozen array with objects with unfrozen properties,
    // and parse `meta` along the way
    goodsIssued = [...goodsIssued.map(entry => ({...entry, meta: JSON.parse(entry.meta)}))];

    // Done!
    console.log(goodsIssued);
})()
.catch(error => {
    console.error(error);
});
.as-console-wrapper {
    max-height: 100% !important;
}

或者,如果您确实想要包装对象:

// 1. Get the object
let obj = await /*...get the goods...*/;

// 2. Create a new, unfrozen object with an unfrozen array with objects with unfrozen properties,
// and parse `meta` along the way
obj = {...obj, goodsIssued: [...obj.goodsIssued.map(entry => ({...entry, meta: JSON.parse(entry.meta)}))]};

实例:

async function getTheGoods() {
    return Object.freeze({
        "goodsIssued": Object.freeze([
            Object.freeze({
                "minted": false,
                "_id": "5e3163597fd0ad2113bcdefe",
                "category": "gameco11",
                "goodId": 64,
                "issuedTo": "player2",
                "memo": "this is a test token",
                "meta": "{\"data\": \"text\", \"test\":1, \"works\": true}",
                "tokenName": "token5",
                "createdAt": "2020-01-29T10:50:01.257Z",
                "updatedAt": "2020-01-29T10:50:01.257Z",
                "__v": 0
            }),
            Object.freeze({
                "minted": false,
                "_id": "5e3163587fd0ad2113bcdefd",
                "category": "gameco11",
                "goodId": 63,
                "issuedTo": "player2",
                "memo": "this is a test token",
                "meta": "{\"data\": \"text\", \"test\":1, \"works\": true}",
                "tokenName": "token5",
                "createdAt": "2020-01-29T10:50:00.691Z",
                "updatedAt": "2020-01-29T10:50:00.691Z",
                "__v": 0
            })
        ])
    });
}

// (Your code is apparently in an `async` function)
(async () => {
    // 1. Get the object
    let obj = await getTheGoods();

    // 2. Create a new, unfrozen object with an unfrozen array with objects with unfrozen properties,
    // and parse `meta` along the way
    obj = {...obj, goodsIssued: [...obj.goodsIssued.map(entry => ({...entry, meta: JSON.parse(entry.meta)}))]};

    // Done!
    console.log(obj);
})()
.catch(error => {
    console.error(error);
});
.as-console-wrapper {
    max-height: 100% !important;
}

<小时/>

不过,您可能不需要 #1 或 #2(或者您可能确实需要两者),具体取决于实际问题是什么。

关于javascript - TypeScript:将字符串转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59965355/

相关文章:

javascript - 使用 ARI 监视与桥梁相关的事件

javascript - 如何解决在 Android 中运行 NativeScript 应用程序时出现的问题?

javascript - 帮助提交表格。将结果加载到内容 div

javascript - 是否可以从 google Plus Badge(添加到圈子)获得回调?

javascript - 如何使用 Node.js、websocket 和total.js 将数据传递到 Mongodb

TypeScript 不应发出类型引用

reactjs - 将默认导入文件从 index.ts 更改为 index.native.ts [react-native]

Javascript 模块模式 : How to inject/create/extend methods/plugin to our own library?

javascript - 选择带有选项的菜单无法识别页面

node.js - Node : Check if a file is locked without locking the file