TypeScript:将字符串转换为对象

时间:2020-01-29 10:42:36

标签: 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 个答案:

答案 0 :(得分:0)

我看到了两种可能,可能是问题所在,或者甚至可能是两者的结合。

  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(或者可能确实需要两者)。