Skip to content
Advertisement

convert/rename keys in object?

I have an object looking like:

const test = {
  picture_905_position: 'right',
  picture_626_position: 'right',
  picture_953_position: 'left'
}

I would like to rename all keys to be

const test = {
  metric[picture_905_position]: 'right',
  metric[picture_626_position]: 'right',
  metric[picture_953_position]: 'left'
}

I’ve come up with this so far, which fails, likely because it’s not valid 🙂 So how do i rename the key and assign the correct value?

const test = {
  picture_905_position: 'right',
  picture_626_position: 'right',
  picture_953_position: 'left'
}
const metrics = [];

let newTest = Object.keys(test).map(key => {
    return 'metric['+key+']' = test[key]
});

console.log(newTest)

Advertisement

Answer

You can reduce over the Object.entries to create a new object (not an array which is what you were trying to do).

const test = {
  picture_905_position: 'right',
  picture_626_position: 'right',
  picture_953_position: 'left'
}

let newTest = Object.entries(test).reduce((acc, [key, value]) => {
    return { ...acc, [`metric[${key}]`]: value };
}, {});

console.log(newTest)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement