Home > OS >  How to add / modify a object key-value at a specific position?
How to add / modify a object key-value at a specific position?

Time:12-28

I need to add / modify an object value to a specific position. The object will be converted to YAML. That is why the position matters, although it is an object and not an array.

So the object should have a version key at the second position:

{
    "$schema": "../../../project-schema.json",
    "version": "1.2.3", // <- add this or move to this position with modified value
    "sourceRoot": "apps/backend/src",
    "projectType": "application"
}

Maybe the version is totally missing

{
    "$schema": "../../../project-schema.json",
    "sourceRoot": "apps/backend/src",
    "projectType": "application"
}

or it is at the wrong position

{
    "$schema": "../../../project-schema.json",
    "sourceRoot": "apps/backend/src",
    "projectType": "application",
    "version": "1.2.3"
}

I tried to use a reduce function on the object keys, but this works only if the version key is missing at all:

const insertKey = (key, value, obj, pos) => {
  return Object.keys(obj).reduce((ac, a, i) => {    
    if (i === pos) ac[key] = value
    ac[a] = obj[a]
    return ac
  }, {})
}

insertKey('version', '2.3.4', obj, 1)

CodePudding user response:

let obj = {
    "$schema": "../../../project-schema.json",
    "sourceRoot": "apps/backend/src",
    "version": "1.2.3", // <- add this or move to this position with modified value
    "projectType": "application"
}
const insertKey = (key, value, obj, pos) => {
  return Object.keys(obj)
  .filter(k  => k!== key) // just add a filter to remove the key 
  .reduce((ac, a, i) => {    
    if (i === pos) ac[key] = value
    ac[a] = obj[a]
    return ac
  }, {})
}

let result = insertKey('version', '2.3.4', obj, 1)

console.log(result)

  • Related