Home > OS >  mapping keys of Object in javascript
mapping keys of Object in javascript

Time:02-17

I would like to change key names in such object:

const data = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4',
}

with those keys from map:

const map = {
'key1': 'change1',
'key4': 'change4'
}

Using code below:

const replacedKeysInData = Object.keys(data).map((key) => {
const keyFromMap = map[key] || key;
return { [keyFromMap]: data[key] }
})
console.log(replacedKeysInData);

I get:

[
{ change1: 'value1' },
{ key2: 'value2' },
{ key3: 'value3' },
{ change4: 'value4' }
]

The point is that I would like to have it in one object:

{ 
change1: 'value1',
key2: 'value2',
key3: 'value3',
change4: 'value4' 
}

I suppose it is simple, how can I do it? Thanks

CodePudding user response:

you are using map which returns an array. I created an empty object and added the keys in a forEach

const data = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4',
}
const map = {
'key1': 'change1',
'key4': 'change4'
}

const replacedKeysInData ={} 
Object.keys(data).forEach((key) => {
const keyFromMap = map[key] || key;
replacedKeysInData[keyFromMap] = data[key]
})
console.log(replacedKeysInData);

CodePudding user response:

const data = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4',
}

const map = {
  'key1': 'change1',
  'key4': 'change4'
}

const replacedKeysInData = Object.entries(data).map(val => {
  if (Object.keys(map).includes(val[0])) {
    return [map[val[0]], val[1]]
  } else {
    return val
  }
});

const newData = Object.fromEntries(replacedKeysInData);

console.log(newData)

CodePudding user response:

It doesn't have to be anything complicated. Just iterate over the object, swap keys, and delete the original.

const data={key1:"value1",key2:"value2",key3:"value3",key4:"value4"},map={key1:"change1",key4:"change4"};

for (const key in data) {
  if (map[key]) {
    data[map[key]] = data[key];
    delete data[key];
  }
}

console.log(data);

  • Related