0

I would like to change key of an object without impacting the other keys as other keys are already aligned with the type array. here I have an object

// Current Object
var obj = {
    "Severity": [
        "minor",
        "critical"
    ],
    "Type": [
        "communication",
        "operational",
        "qos"
    ],
    "Date Time": {
        "gte": "2023-01-12",
        "lte": "2023-01-13"
    }
}

and I want to change "date time" key to this

//Desired Result
var obj = {
    "Severity": [
        "minor",
        "critical"
    ],
    "Type": [
        "communication",
        "operational",
        "qos"
    ],
    "Date Time": [
        "2023-01-12 2023-01-13"
    ]
}

I am using Objecy.keys but not getting the desired result. Is it the right way or not? need help, Thanks!

Object.keys(obj).forEach((item) => {
   if(item == "Date Time"){
       obj[item] =  obj[item].gte + " " + obj[item].lte;
     }
   })

Snippet:

var obj = {
  "Severity": [
    "minor",
    "critical"
  ],
  "Type": [
    "communication",
    "operational",
    "qos"
  ],
  "Date Time": {
    "gte": "2023-01-12",
    "lte": "2023-01-13"
  }
}

Object.keys(obj).forEach((item) => {
  if (item == "Date Time") {
    obj[item] = obj[item].gte + " " + obj[item].lte;
  }
})

console.log(obj)
Konrad
  • 21,590
  • 4
  • 28
  • 64
SanjuBaba
  • 37
  • 11

1 Answers1

1

You forgot []

var obj = {
  "Severity": [
    "minor",
    "critical"
  ],
  "Type": [
    "communication",
    "operational",
    "qos"
  ],
  "Date Time": {
    "gte": "2023-01-12",
    "lte": "2023-01-13"
  }
}

Object.keys(obj).forEach((item) => {
  if (item == "Date Time") {
    obj[item] = [obj[item].gte + " " + obj[item].lte];
  }
})

console.log(obj)

Same thing but shorter

var obj = {
  "Severity": [
    "minor",
    "critical"
  ],
  "Type": [
    "communication",
    "operational",
    "qos"
  ],
  "Date Time": {
    "gte": "2023-01-12",
    "lte": "2023-01-13"
  }
}

const o = obj['Date Time']

obj['Date Time'] = [o.gte + " " + o.lte];


console.log(obj)
Konrad
  • 21,590
  • 4
  • 28
  • 64