0

I created a form to get some info from User, and I want to move some of their info into a nested object. the reason why is to better organize my data later in front-end.

As a simple example, how to create the following "newInfo" out of "oldInfo" in JavaScript?

oldInfo = {
  name: 'John',
  Age: '32',
  friend1: 'Michael',
  friend2: 'Peter',
};

newInfo = {
  name: 'John',
  Age: '32',
  friends: {
    friend1: 'Michael',
    friend2: 'peter',
  },
};

I'm sure this must be a repeated and simple topic, but I couldn't find any as I didn't know what keyword to search for.

3 Answers 3

2

You could explicitly assign it

const oldInfo = {
  name: "John",
  Age: "32",
  friend1: "Michael",
  friend2: "Peter",
}

const newInfo = {
  name: oldInfo.name,
  Age: oldInfo.Age,
  friends: {
    friend1: oldInfo.friend1,
    friend2: oldInfo.friend2,
  },
}

console.log(newInfo)

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

1 Comment

Thanks, works fine, but since the number of fields in friend:name are dynamic (the example above was simplified to better show my problem) I need to use a code rather than assigning them explicitly
2

You can do this easily with spread operator:

const { name, Age, ...friends } = oldInfo;
newInfo = { name, Age, friends };

It simply extracts all fields except name and age as friends.

Example:

const oldInfo = {
  name: 'John',
  Age: '32',
  friend1: 'Michael',
  friend2: 'Peter',
};
const { name, Age, ...friends } = oldInfo;
const newInfo = { name, Age, friends };
console.log(newInfo);

Comments

0

If you have a dynamic number of friend: name key-value pairs and other properties that shouldn't be nested into friends then you can use Object.entries and reduce:

const oldInfo = {
  name: 'John',
  Age: '32',
  friend1: 'Michael',
  friend2: 'Peter',
};

const newInfo = Object.entries(oldInfo).reduce((acc, [k, v]) => {
  if(k.startsWith('friend')) {
    acc.friends ? acc.friends[k] = v : acc.friends = {[k]: v};
  } else {
    acc[k] = v;
  }
  return acc;
},{});

console.log(newInfo);

2 Comments

Thanks Ramesh, creative code, the only problem is that in my example I wrote above all keys start with friend (friend1, friend2...) yet in my actual problem there are other keys which are not alphabetically similar. This method though is very useful and I definitely use it in my other problems
@Babak Happy to help. You can update your question with the actual object if you want an answer for that.

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.