json 需要根据另一个对象数据来格式化对象[已关闭]

pu82cl6c  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(90)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

昨天关门了。
此帖子已于昨天编辑并提交审阅,无法重新打开帖子:
原始关闭原因未解决
Improve this question
使用此对象,它是API的结果(列是动态的)

let json1 ={
    "records": [
        {
            "ID": "1",
            "Value": "A005",
        },
        {
            "ID": "2",
            "Value": "A007",
        },
        {
            "ID": "3",
            "Value": "B001",
        },
        {
            "ID": "4",
            "Value": "B003",
        },
    ],
    "conditional":[
    {"Value":{'A005':'red','A007':'blue','B001':'green'}},
    ]
}

我需要下面的对象来格式化要在UI中表示的数据

let json ={
    "records": [
        {
            "ID": "1",
            "Value": "<span style='color;red'>A005</span>",
        },
        {
           "ID": "2",
           "Value": "<span style='color;blue'>A007</span>",
        },
        {
          "ID": "3",
          "Value": "<span style='color;green'>B001</span>",
        },
        {
            "ID": "4",
            "Value": "B003",
        },
    ],
    "conditional":[
    {"Value":{'A005':'red','A007':'blue','B001':'green'}},
    ]
}

条件和记录中的数据是动态的。“值”可以是任何列名,也可以有任意数量的列。所有数据都是动态的

dfty9e19

dfty9e191#

我们可以通过Array.forEach()来实现

let json ={
    "records": [
        {
            "ID": "1",
            "Value": "A005",
        },
        {
            "ID": "2",
            "Value": "A007",
        },
        {
            "ID": "3",
            "Value": "B001",
        },
        {
            "ID": "4",
            "Value": "B003",
        },
    ],
    "conditional":[
    {"Value":{'A005':'red','A007':'blue','B001':'green'}},
    ]
}

// PS: conditional format seems not elegant,especially []
let conditional = json.conditional[0].Value

json.records.forEach(e => {
  let color = conditional[e.Value] 
  e.value = `<span style='color:${color}'>` + e.Value + `</span>`
})

console.log(json)

相关问题