简体   繁体   English

更新数组的 object 的属性

[英]Update properties of an object of an array

I have an array of objects and I need to update a few properties of a specific object inside the array and then run the findAndUpdateById call on it.我有一个对象数组,我需要更新数组中特定 object 的一些属性,然后对其运行findAndUpdateById调用。 I am trying to do this but its not updating and gives me an error of undefined name property.我正在尝试这样做,但它没有更新并给我一个未定义名称属性的错误。 I guess I am not following the right procedure to update an update an object of javascript and because of this i need help.我想我没有遵循正确的程序来更新 javascript 的 object 的更新,因此我需要帮助。 Here is my array这是我的数组

let arr = [
  {
    "_id": "1234",
    "customer": {
      "firstName": "John",
      "lastName": "Doe",
      "email": "johndoe@gmail.com",
      "address": "123 Caroline Street"
    }
  }  
]

Now I am recieving parameter like this that i need to update in my object现在我收到这样的参数,我需要在我的 object 中更新

let ctx = {
  "params": {
      "changeObject": {
        "firstName": "Ali",
        "email": "ali@gmail.com"
      }
  }
}

Given: " I am getting the array of object by making.find call against id and there will be only one customer object in the received array "给定:“我通过对 id 进行调用获取 object 数组,接收到的数组中只有一个客户 object

 // Given let arr=[{"_id":"1234","customer":{"firstName":"John","lastName":"Doe","email":"johndoe@gmail.com","address":"123 Caroline Street"}}]; let ctx={"params":{"changeObject":{"lastName":"Ali"}}}; arr[0].customer = Object.assign(arr[0].customer, ctx.params.changeObject); console.log(arr);

I think you were using different properties changePayload and changeObject .我认为您使用了不同的属性changePayloadchangeObject

You may want to use the spread operator and map for this as well.您可能还想为此使用扩展运算符和 map。

 let arr = [ { "_id": "1234", "customer": { "firstName": "John", "lastName": "Doe", "email": "johndoe@gmail.com", "address": "123 Caroline Street" } } ]; let ctx = { "params": { "changePayload": { "firstName": "Ali", "email": "ali@gmail.com" } } } arr = arr.map( data => ({...data, customer: {...data.customer, ...ctx.params.changePayload} }) ); console.log( arr );

NOTE: This will change all objects in your array, but that is what you were asking for.注意:这将更改数组中的所有对象,但这正是您所要求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM