Reputation: 647
I have this object
myObject = {
id: "44",
name: "name",
firstName: "fn",
lastName: "tt",
cars: [],
houses: [],
family: {}
}
I want to format this object to
myObject = {
person: {
id: "44",
name: "name",
firstName: "fn",
lastName: "tt"
},
cars: [],
houses: [],
family: {}
}
Is there anyway i can do this without using delete
?
Upvotes: 0
Views: 178
Reputation: 56770
You can destructure what you need, put the rest into a variable rest
, and then re-assign myObject
:
let myObject = {
id: "44",
name: "name",
firstName: "fn",
lastName: "tt",
cars: [],
houses: [],
family: {}
}
const {id, name, firstName, lastName, ...rest } = myObject;
myObject = {
person: { id, name, firstName, lastName },
...rest
}
console.log(myObject);
Upvotes: 0
Reputation: 5629
You can use destructuring
:
const myObject = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
const { houses, cars, family, ...rest } = myObject
const myNewObject = {
person: rest,
houses,
cars,
family
}
console.log(myNewObject)
Upvotes: 4
Reputation: 12209
You could create a new object and assign the properties to it:
let obj = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
//I want to format this object to
//myObject = { person: {id:"44", name:"name", firstName:"fn", lastName:"tt"}, cars: [], houses:[], family:{}}
let res = {}
res.person = {id: obj.id, name: obj.name, firstName: obj.firstName, lastName: obj.lastName}
res.cars = obj.cars
res.houses = obj.houses
res.family = obj.family
console.log(res)
Upvotes: 0
Reputation: 8611
You can use destructuring assignments to decompose your object into variables and restructure them in a simple function.
const format = (obj) => {
const {id, name, firstName, lastName, ...props} = obj;
return {person: {id, name, firstName, lastName}, ...props}
}
const formatted = format(myObject);
console.log (formatted)
<script>
var myObject = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
</script>
Upvotes: 1