-2

Using this Object which is a result from the API ( Columns are dynamic )

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'}},
    ]
}

I need the below Object to format the data to represent in the 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'}},
    ]
}

Data inside conditional and records are dynamic. 'Value' can be any column name, it can also have any number of columns. All data are dynamic

  • 1
    Nothing in your question has anything to do with JSON. See [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Ivar Nov 29 '22 at 10:03

1 Answers1

2

We can do it via 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)
flyingfox
  • 13,414
  • 3
  • 24
  • 39