I need to object to server but need to format
example of object ->
let obj =
{
id: 1,
title: title
}
This is okay butt any time i got different property
I need to format if I got name property i need to replace instead title
if i got name i need to format object
let obj =
{
id: 1,
name: name
}
Title property i got always but when i got name i need to replace...
i am try with:
if(name){
return name: name
} else {
return title: title
}
You can create a function to do it:
function createObj(id, s, isName = false){
let obj = {id: id};
if(isName){
obj.name = s;
} else {
obj.title = s;
}
return obj;
}
You can then call that function like this:
let o1 = createObj(1, 'Person', true); // {id: 1, name: 'Person'}
let o2 = createObj(2, 'CEO', false); // {id: 2, title: 'CEO'}
console.log(o1); // Outputs: {id: 1, name: 'Person'}
console.log(o2); // Outputs: {id: 2, title: 'CEO'}
I think you can do this with the hasOwnProperty(prop) function.
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Have a look at the attached code:
// consider a list of objects
// some objects contain the property 'title'
// while the rest of them have the property 'name'
let objects =
[
{
id: 1,
title: "it is title"
},
{
id: 2,
name: "it is name"
}
]
// iterate through each object
// and replace its 'name' property
// with the 'title' property
objects.forEach(obj => {
// does object has the property 'name'?
// if yes, replace it with the property 'title'
if(obj.hasOwnProperty('name')){
// set value of the property 'title'
obj.title=obj.name;
// delete the property 'name'
delete obj.name;
}
})
// log all objects for testing
objects.forEach(obj => {
console.log(obj.id, obj.title)
})