将json对象数组解析为特定格式

时间:2019-04-22 09:51:50

标签: javascript arrays json

我已经将json对象的数组解析为一种特定的格式,但是我需要根据条件动态改变对象的“ type”属性值。

    input >>
    [
      {
        "accident_description": "bike accident",
        "reported_by": "john",

      },
       {
        "accident_description": "car accident",
        "reported_by": "sam",

      }
    ]

    output >>
    "fields": [
        {
          "title": "accident_description",
          "values": "bike accident"
          "type": "generic",

        },
        {
          "title": "reported_by",
          "values": "john",
          "type": "generic",

        },
        {
          "title": "accident_description",
          "values": "car accident"
          "type": "generic",

        },
        {
          "title": "reported_by",
          "values": "sam",
          "type": "generic",

        },
      ]

我已经尝试过了,并且效果很好

const arr = [ { "accident_description": "bike accident", "reported_by": "john", }, { "accident_description": "car accident", "reported_by": "sam", } ];
 let res = arr.flatMap(x => (Object.entries(x).map(([k,v]) => ({title:k,values:v,type:"generic"}))));
   console.log(res);

但是这里的类型是固定的,根据下面给出的条件,我需要将“ type”值设为动态。

if(title=='accident_description')
type:generic
else
type:custom

1 个答案:

答案 0 :(得分:1)

只需使用三元运算符。代替

{title:k,values:v,type:"generic"}

{title:k,values:v,type:(title=='accident_description') ? 'generic' : 'custom'}

如果逻辑比简单的条件更为复杂,请记住,您在map中使用的arrow函数可以在主体中包含任意代码,因此您可以执行所需的任何计算和return所需的最终type值。