1

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

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.