简体   繁体   English

在 JavaScript 的循环内更改 object 值

[英]Change an object value inside a loop in JavaScript

I have an array of objects like this:我有一个这样的对象数组:

const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]

I have to change each item name property to something like this:我必须将每个项目名称属性更改为如下所示:

...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}

My attempt is to loop object like following:我的尝试是循环 object,如下所示:

data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})

But this always console the original item and the name property value is not modified.但这总是控制台原始项目并且 name 属性值没有被修改。

const newData = data.map(user => ({ _id: user._id, name: { en: user.name } }))

try somthing like:尝试类似的东西:

const newList = data.map(obj => {
return { _id: obj._id, name: { en: obj.name } }
});

and the newList list is your new data list so you can do it:并且 newList 列表是您的新数据列表,因此您可以这样做:

data = newList;

EDIT:编辑:

if you have more properties you can change the return line to:如果您有更多属性,您可以将返回行更改为:

return { ...obj, name: { en: obj.name } }

what will happen here, it will deploy all the object properties as they are, and modify the name property, unfortunately, every property you want to modify, you have to re-write it.这里会发生什么,它将按原样部署所有 object 属性,并修改 name 属性,不幸的是,您要修改的每个属性都必须重新编写。

I created a library to express transformations like this very simply.我创建了一个库来非常简单地表达这样的转换。

const { pipe, fork, get } = require('rubico')

const data = 
    [ { _id: '49847444033', name: 'yoko'} 
    , { _id: '49847433333', name: 'doira'} 
    ]

const onData = pipe([
  fork({
    _id: get('_id'), // data => data._id
    name: fork({ en: get('name') }), // data => ({ en: data.name })
  }),
  console.log,
])

data.map(onData) /*
{ _id: '49847444033', name: { en: 'yoko' } }
{ _id: '49847433333', name: { en: 'doira' } }
*/

I've commented the code above, but to really understand rubico and get started using it, I recommend you read the intuition and then the docs我已经评论了上面的代码,但要真正理解 rubico 并开始使用它,我建议你先阅读直觉,然后再阅读文档

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

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