Rory Rory - 24 days ago 7
jQuery Question

JavaScript build a dynamic object

I have a var named

onversation
that contains this:

{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}


I also have an object named
person
that contains this:

{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}


What I'd like is to have a combined object called
result
that looks like this

result {
conversation {
conversationId : adbabc54-3308-436d-a48b-932f4010d3c6,
participantId : 415651e6-f0a5-4203-8019-4f88c3ed9cd5
},
person {
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
}


How would I do this dynamically whereby the result object is built using the name of the var 'conversation' and name of the object 'person' ?

Also, the length of either conversation or person can be any length.
Pure JavaScript if possible , but could use underscore etc.

Answer

If I understand your question correctly, you can use object shorthand notation which is supported in most browsers (Probably all of them, except IE11) for simplifying your solution even more:

var conversation = 
{
    conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
    participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person = 
{
    firstname: "fred",
    surname: "smith",
    age: "21", 
    gender: "male"
};

var result = { conversation, person }

console.log(result)

Comments