JavaScript构建一个动态对象

时间:2016-11-11 11:04:05

标签: javascript jquery

我有一个名为onversation的var,其中包含:

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

我还有一个名为person的对象,其中包含:

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

我想要的是一个名为result的组合对象,看起来像这样

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

我将如何动态地执行此操作,从而使用var'conversation'的名称和对象'person'的名称构建结果对象?

此外,会话或人的长度可以是任何长度。 如果可能的话,纯JavaScript,但可以使用下划线等。

4 个答案:

答案 0 :(得分:3)

试试吧

var result = {
 'conversation': conversation,
 'person': person
}

动态

var result = {}

result['person'] = person

resilt.person = person

答案 1 :(得分:2)

如果我正确理解了您的问题,您可以使用大多数浏览器支持的对象速记符号(可能所有这些都是IE11除外),以便进一步简化您的解决方案:

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)

修改 如果仅变量名称发生变化,并且属性名称保持不变或具有某种唯一键,则可以在对象的键上使用 for loop

例如:

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

var result = { someConversationVariableName, somePersonVariableName }

for (key in result) {  
  if(result[key]['conversationId']) {
    console.log(`Found conversation object. It's name is: ${key}`);
  }
  else if(result[key]['firstname']) {
    console.log(`Found person object. It's name is: ${key}`);
  }
}
  

答案 2 :(得分:1)

如果您需要推迟添加对象,您也可以采用这种方法:

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 = {};

result['conversation'] = conversation;
result['person'] = person;

console.log(result);

答案 3 :(得分:0)

这必须奏效: -

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': conversation,
 'person': person
}