viewist
viewist

Reputation: 87

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)

Upvotes: 0

Views: 79

Answers (3)

Tushar Shahi
Tushar Shahi

Reputation: 20451

You are on the right track when you iterate through the object keys. But .map() returns an array. You can use forEach() to perform an action based on each

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

Object.keys(test).forEach(key => {
     ans['metric['+key+']'] = test[key]
});

Note: This does not modify the original object. You can also do that using the same object instead of ans and delete operator.

Upvotes: 0

Andy
Andy

Reputation: 63524

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)

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You can't use map here because the map will return an array of something(what you're returning) and you want the result in an object.

You can use reduce and template Literal to get the desired result.

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

const result = Object.keys(test).reduce((acc, curr) => {
  acc[`metric[${curr}]`] = test[curr];
  return acc;
}, {});

console.log(result);

Upvotes: 1

Related Questions