Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to loop and change key name?

How can I change key name but key its values?

For instance I have this json data that I have stored:

{ particles: 
   { name: 'particles',
     values: [ [Object], [Object], [Object], [Object], [Object] ] },
  timestamps: 
   { name: 'timestamps',
     values: [ [Object], [Object], [Object], [Object], [Object] ] } 
}

And I will loop this input and change the key:

{ particles: 'particle', timestamps: 'timestamp' }

Change particles to particle and timestamps to timestamp

My attemp:

for (var property in data) {
   stored[data[property]] = stored[property].values;
   stored[property].name = data[property];
}

I only managed to change the name's value inside the stored data but not the key name...

Any ideas?

like image 411
Run Avatar asked Jul 01 '26 01:07

Run


2 Answers

Assign new property by getting old property value and then delete old property.

var data = {
  particles: {
    name: 'particles',
    values: []
  },
  timestamps: {
    name: 'timestamps',
    values: []
  }
}

var newK = {
  particles: 'particle',
  timestamps: 'timestamp'
};

// get all object keys and iterate over them
Object.keys(newK).forEach(function(ele) {
  // assign object property based on old property value
  data[newK[ele]] = data[ele];
  // update name property
  data[newK[ele]].name = newK[ele];
  // delete old object property
  delete data[ele];
})

console.log(data);
like image 158
Pranav C Balan Avatar answered Jul 03 '26 13:07

Pranav C Balan


You can achieve it by iterating the data and create the new keys and delete the old ones.

E.g.

var data = {
    particles: {
        name: 'particles',
        values: [ [Object], [Object], [Object], [Object], [Object] ]
    },
    timestamps: {
        name: 'timestamps',
        values: [ [Object], [Object], [Object], [Object], [Object] ]
    } 
};

var res = { particles: 'particle', timestamps: 'timestamp' };

for (var k in res) {
    var newValue = res[k];
    data[newValue] = data[k];
    data[newValue].name = newValue;
    delete data[k];
}
like image 35
choz Avatar answered Jul 03 '26 15:07

choz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!