【问题标题】:Convert React/javascript string array of objects to array of objects将 React/javascript 字符串对象数组转换为对象数组
【发布时间】:2020-12-05 23:22:30
【问题描述】:

这似乎是一个微不足道的问题,但我无法让它正常工作。我对 JS/React 还很陌生,所以这也对我不利。

这是我得到的响应(它是一个 TS 对象类型,但实际上是一个纯字符串,所以我无法迭代它,它只是没用):

[{"answer": "Within 2 weeks", "question": "Moving/Purchase date"}, {"answer": "2 bedrooms", "question": "Bedrooms (minimum) ?"}]

如何将其转换为对象数组以便遍历它们?像这样;

[
    0: { "answer": "Yes", "question": "Are you sure?" },
    1: { "answer": "False", "question": "Do you hold a valid passport?" }
]

我尝试过 JSON.parse 并创建一个 Map,但它没有提供预期的输出。任何帮助将不胜感激。谢谢大家! :)

【问题讨论】:

  • 它已经是一个数组......如果你的意思是它是一个 JSON 字符串,那么只需 JSON.parse 它,但从打字来看,它似乎已经是一个数组。

标签: javascript arrays json reactjs string


【解决方案1】:

你考虑过eval吗?

当然,如果您的系统允许执行任意 Javascript 代码,则使用它是有风险的,但如果您确定从字符串运行代码,则在此处转换代码(如果它是一行代码,则在其中的数组) 字符串中的数组对象对您的环境无害,请使用它。

let str = '[{"answer": "Within 2 weeks", "question": "Moving/Purchase date"}, {"answer": "2 bedrooms", "question": "Bedrooms (minimum) ?"}]';

let obj = eval(str);
console.log(obj, typeof(obj));

for (const element of obj){
    console.log(element);
} ;

我用过JSON.parse,它似乎也可以工作(推荐选项):

let str = '[{"answer": "Within 2 weeks", "question": "Moving/Purchase date"}, {"answer": "2 bedrooms", "question": "Bedrooms (minimum) ?"}]';

let obj = JSON.parse(str);
console.log(obj, typeof(obj));

for (const element of obj){
    console.log(element);
} ;

【讨论】:

    【解决方案2】:

    我设法使用以下方法对其进行了排序:

    const arrayObj = JSON.parse(results as unknown as string);
    

    【讨论】:

      【解决方案3】:

      如果你想将它包装在另一个以索引为键的对象中,那么你可以使用 reduce。

      const list = [{
        "answer": "Within 2 weeks",
        "question": "Moving/Purchase date"
      }, {
        "answer": "2 bedrooms",
        "question": "Bedrooms (minimum) ?"
      }]
      
      const newList = list.reduce((acc, x, i) => [...acc, {
        [i]: x
      }], []);
      
      console.log(newList)

      【讨论】:

      • 我非常怀疑这就是问题所要求的。
      猜你喜欢
      • 2017-08-24
      • 2013-04-19
      • 1970-01-01
      • 2018-09-25
      • 2014-03-12
      • 2012-05-08
      • 2022-10-07
      • 1970-01-01
      • 2021-05-09
      相关资源
      最近更新 更多