0

I have an object that I want to use the keys as keys in a new object and the value into a child object. How could I go from A to Z?

const a = {key1: 'text', key2: 'text2'}

const z = [{ key1: { similarTo: 'text' } }, {key2: {similarTo: 'test2'}}] 
1
  • I meant how to get const a to look like const z Commented Oct 28, 2019 at 23:30

1 Answer 1

4

You can use Object.entries and Array.prototype.map in order to achieve it:

const a = {key1: 'text', key2: 'text2'};
const z = Object.entries(a).map(([k, v]) => ({ [k]: { similarTo: v } }));

console.log(z);

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

4 Comments

I like this, but find ... .map(([k, v]) => ({ [k]: { similarTo: v } })) easier to understand
Is there also a way I could add a switch statement in there to check what the key so that I could change the similarTo to something else?
@ScottSauyet - I agree and therefore edited my answer. Thank you.
@bananapancakes3 - You can switch inside the map clause if you really want to.

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.