1

Say i have the following object:

obj1 = {
   'patato la blaza' : {
        'weight' : 5,
        'height' : 90
    },
    'apple ibiza' : {
        'weight' : 3,
        'height' : 84
    }
}

I would like to run through the keys and modify them, I.E. change the key values, how do i go about doing this in javascript/jQuery ? , i know i can modify the value like so:

$.each(obj1 , function(i , e){
   obj1[i] = "someramdomvalue"
});

But i don't quite understand how would i go about change/manipulating the values of the keys, in the object provided above i would like to change the value of patato la blaza to just patato and apple ibiza to apple , i will use a regex to get the shortened version , but i don't know how to add these shortened values as the new key in the object. would appreciate any help.

NOTE::- i have searched SO already but most of the questions pertain to how to change the value of the value ob an object and not the keys

Alexander Solonik
  • 9,466
  • 17
  • 65
  • 157
  • 2
    Possible duplicate of [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – messerbill Mar 23 '18 at 11:52

4 Answers4

5

I'd use reduce on the Object.keys()

let obj = {
  'patato la blaza': {
    'weight': 5,
    'height': 90
  },
  'apple ibiza': {
    'weight': 3,
    'height': 84
  }
};

obj = Object.keys(obj).reduce((a, b) => {
  a[b.substring(0, b.indexOf(' '))] = obj[b];
  return a;
}, {});

console.log(obj);
baao
  • 67,185
  • 15
  • 124
  • 181
2

Probably something along those lines:

const obj1 = {
   'patato la blaza' : {
        'weight' : 5,
        'height' : 90
    },
    'apple ibiza' : {
        'weight' : 3,
        'height' : 84
    }
};
// Example key transform
const transform = x => x.split(" ")[0];

Object.keys(obj1).forEach(key => {
    const val = obj1[key];
    delete obj1[key];
    obj1[transform(key)] = val;
});

console.log(obj1);
H.B.
  • 142,212
  • 27
  • 297
  • 366
2

Create a map of all the changes you want and build a new object with the new keys names:

var obj = {
   'patato la blaza' : {
        'weight' : 5,
        'height' : 90
    },
    'apple ibiza' : {
        'weight' : 3,
        'height' : 84
    }
};

var changes = {
  'patato la blaza': 'potato',
  'apple ibiza': 'apple'
}

var res = Object.assign({}, ...Object.entries(obj).map(([prevKey, val]) => ({[changes[prevKey]]: val})));

console.log(res);
Faly
  • 12,802
  • 1
  • 18
  • 35
1

If you want to use $.each(), I would create a new property with the desired key, copy the value of the existing property and then delete the old property:

$.each(obj1 , function(i , e){
   obj1["somenewkey"] = obj1[i];
   delete obj1[i];
});
TLP
  • 1,192
  • 1
  • 6
  • 18