根据子对象中的id将对象插入子数组

时间:2017-09-19 09:53:55

标签: javascript lodash

我的会话对象如下,

{
  "buyer": {
    "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "Name": "John"
  },
  "seller": {
    "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "Name": "Doe"
  },
  "conversationId": "2c418465-1154-4153-850b-4ea504877c36",
  "messages": [{
    "date": "12/23/2013",
    "text": "hi how is it going\n",
    "receiverId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "senderId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c"
  }]
}

在上面我需要替换messages对象,我需要通过检查对话Object中的id并添加一个名为sender的新属性并分配它。

输出将是:

{
  "buyer": {
    "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "Name": "John"
  },
  "seller": {
    "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "Name": "Doe"
  },
  "conversationId": "2c418465-1154-4153-850b-4ea504877c36",
  "messages": [{
    "date": "12/23/2013",
    "text": "hi how is it going\n",
    "receiverId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "senderId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "sender": {
      "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
      "Name": "John"
    },
    "reciever": {
      "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
      "Name": "Doe"
    }
  }]
}

我尝试使用for循环,效果很好。但有没有办法使用loadash或vanila javascript在几行中完成它?

1 个答案:

答案 0 :(得分:1)

您可以map您的对象messages并相应地对其进行转换:

obj.messages.map(function(m){
    if(m.senderId === obj.buyer.userId){
      m.sender = Object.assign({}, obj.buyer);
      m.receiver = Object.assign({}, obj.seller);
    }else if(m.senderId === obj.seller.userId){
      m.sender = Object.assign({}, obj.seller);
      m.receiver = Object.assign({}, obj.buyer);
    }
    return m;
});

<强>演示:

这是一个有效的演示:

&#13;
&#13;
var obj = {
  "buyer": {
    "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "Name": "John"
  },
  "seller": {
    "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "Name": "Doe"
  },
  "conversationId": "2c418465-1154-4153-850b-4ea504877c36",
  "messages": [{
    "date": "12/23/2013",
    "text": "hi how is it going\n",
    "receiverId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "senderId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c"
  }]
};

obj.messages.map(function(m){
    if(m.senderId === obj.buyer.userId){
      m.sender = Object.assign({}, obj.buyer);
      m.receiver = Object.assign({}, obj.seller);
    }else if(m.senderId === obj.seller.userId){
      m.sender = Object.assign({}, obj.seller);
      m.receiver = Object.assign({}, obj.buyer);
    }
    return m;
});

console.log(obj);
&#13;
&#13;
&#13;