繁体   English   中英

如何更新数组内的json对象?

[英]How can I update a json object inside of an array?

我有一个对象数组,我想更新一些内容。 我想我可以映射对象,找到我要寻找的匹配项,然后更新它。

data = data.map(obj => {
   return this.state.objToFind === obj.title;   
   }).map(obj, idx) => {
      console.log("found " + obj.title);     // reads found + undefined?
      obj.menu = this.state.menu;
      obj.title = this.state.title;
      obj.content = this.state.content;
 });

但是,这不起作用。 我找到了对象,但obj.anything是未定义的。 我的console.log读取“发现未定义”。

data.map(obj => {
  return this.state.objToFind === obj.title;   
})

第一个映射将返回true和false的数组,第二个映射将循环遍历这些值, console.log("found " + obj.title)将因此显示“ found + undefined”。

也许您想要这样的东西。

data = data.filter(obj => {
   return this.state.objToFind === obj.title;   
   }).map(obj, idx) => {
      console.log("found " + obj.title);
      obj.menu = this.state.menu;
      obj.title = this.state.title;
      obj.content = this.state.content;
      return obj;
 });

将其更改为其他变量而不是obj,因为它引用的是an arrayobj 还要在第一个函数中使用array.filter,它将返回一个数组,

data = data.filter(obj => {
   return this.state.objToFind === obj.title;   
   }).map(newval, idx) => {
      console.log("found " + newval.title);     
      newval.menu = this.state.menu;
      newval.title = this.state.title;
      newval.content = this.state.content;
 });

Map用于返回变异的对象。 使用map时,您需要返回一些东西,以您的情况为修改对象。

但是,有些事情您做错了。 1)您正在使用.map搜索内容(这不是您使用map的方式); 尝试使用.filter或.find 2)使用map更新对象(在第二个函数中)后,您需要将其返回。 情况1:

data = data.filter(obj => {
       return this.state.objToFind === obj.title;   
   }).map(foundObj, idx) => {
          console.log("found " + foundObj.title);
          foundObj.menu = this.state.menu;
          foundObj.title = this.state.title;
          foundObj.content = this.state.content;
      return foundObj; //updated obj
 });

情况2:

    var foundObj = data.find(obj => {
     return this.state.objToFind === obj.title;   
   });
    console.log("found " + foundObjs.title);
    foundObjs.menu = this.state.menu;
    foundObjs.title = this.state.title;
    foundObjs.content = this.state.content;

如果您只想处理使this.state.objToFind === obj.title true的那些元素,那么Array.filter是您所需要的

data = data.filter(obj => {
   return this.state.objToFind === obj.title;   
   }).map(obj, idx) => {
      console.log("found " + obj.title);     // reads found + undefined?
     ...
 });

甚至简单

您可以使用some运算符。 (它通过遍历数组来工作,当您返回true时,它会跳出循环)

data.some(function(obj){
   if (obj.title ==== 'some value'){
        //change the value here
        obj.menu = 'new menu';
        obj.title = 'new title';
        return true;    //breaks out of he loop
   }
});

暂无
暂无

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

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