1

I have an existing object,

this.data = {
   "part": "aircraft",
   "subid": "wing",
   "information.data.keyword": "test",
   "fuel.keyword": "lt(6)"
}

What I'm trying to do is to check every key and if the key has .keyword then I am trying to delete it and create it without .keyword. I am not sure how to rename and push to an existing object.

what I have tried so far,

for(let x in this.data) {      
    if(x.includes('.keyword')) {      
        let xy = x.replace(/.keyword/g, "");
        console.log(xy);
    }
}
nash11
  • 8,220
  • 3
  • 19
  • 55
Dexter
  • 518
  • 3
  • 12
  • 40
  • 2
    The solution is already in the question: _"...to **delete** it and **create** it..."_ - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete – Andreas Sep 17 '19 at 05:28

4 Answers4

2

First you need to create a new key. After assigning value to newly created key you need to delete the old one.

Try this:

 this.data = {
    "part": "aircraft",
    "subid": "wing",
    "information.data.keyword": "test",
    "fuel.keyword": "lt(6)"
  }
  for (let x in this.data) {
    if (x.includes('.keyword')) {
      this.data[x.replace(/.keyword/g, "")] = this.data[x];
      delete this.data[x];
    }
  }
  console.log(this.data)
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
2

Try this

 let data = {
    "part": "aircraft",
    "subid": "wing",
    "information.data.keyword": "test",
    "fuel.keyword": "lt(6)"
  }

  Object.keys(data).forEach((x) => {
    if (x.includes('.keyword')) {

      this.data[x.replace(/.keyword/g, "")] = data[x];
      delete data[x]
    }
});

console.log(data)
Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
2

You have already used includes() and replace(). Just need to delete the object using delete operator as @Andreas mentioned and create new entry.

for(var k in data) {
   if (k.includes(".keyword")) {
      var newKey =  k.replace(/.keyword/g, "");// New key for new entry without .keyword
      data[newKey] = data[k]; //Creating new entry 
      delete(data[k]); //Deleting old entry
   }
}
Inizio
  • 2,226
  • 15
  • 18
1

You could try to copy/clone the object, add it to this.data and then delete the version with .keyword.

qristjan
  • 183
  • 5