0

Let's say there's an object with string values:

const A = { key_a1: "value_a1", key_a2: "value_a2" };

What is the way to clone this object and add some prefix to the values? So I want to convert object A into object B that looks next:

const B = { key_a1: "prefix_value_a1", key_a2: "prefix_value_a2" };

I know about copy syntax like const B = { ...A } but that does not allow to modify values.

3
  • What have you tried? We can probably work out if it's the simplest method. Commented Jul 27, 2022 at 10:47
  • something smilar i had stackoverflow.com/a/72824860/13583510 except you have to map Object.entries(obj).map(([k,v]) => [k,'prefix_'+v]) Commented Jul 27, 2022 at 11:10
  • @Andy well, I should've say that I'm not good in js. I know about copying syntax like const B = { ...A } but other then that I'd want to know what my options are. Probably the word "simplest" in the description is just unnecessary. Commented Jul 27, 2022 at 11:58

2 Answers 2

1

You can use Object.entries to turn the keys and values of the original object into an array, and reduce to create a new Object with the same keys of the original object with a prefix.

const A = { key_a1: "value_a1", key_a2: "value_a2" };

const B = Object.entries(A).reduce((acc, [key, value]) => ({
    ...acc,
    [`prefex_${key}`]: value
  }), {})

console.log(B)

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

Comments

1

You can loop over it's values, like:

Object.values(A).map(i => `prefix_${i}`)

2 Comments

yeah, but this will return the array, not a new object, Probably the answer below is better
You can construct an object from my answer pretty easily, i just showed how to modify the value :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.