Javascript将具有值的新字段添加到数组中的特定对象

时间:2019-05-03 04:33:20

标签: javascript arrays json object

我有一个像这样的json对象数组

{  
   "images":[  
      {  
         "childFolder":[  
            {  
               "name":"Trước",
               "_id":"5ccbc1e4af2be32acd1da1dd"
            },
            {  
               "name":"Sau",
               "_id":"5ccbc1e4af2be32acd1da1dc"
            },
            {  
               "name":"X-Quang",
               "_id":"5ccbc1e4af2be32acd1da1db"
            }
         ]
      }
   ]
}

我想像这样添加值是的现场测试

  

“测试”:“是”

使用JavaScript使用"name" = "Sau"到对象

我该怎么做? 任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:2)

您可以使用Array.forEach遍历数组,然后检查名称“ Sau”并更新对象。

        //Read the CSV FIle
        using (CsvReader csv = new CsvReader(new StreamReader(path), true))
        {
           //Set the missing Field Action.
            csv.MissingFieldAction = MissingFieldAction.ParseError;

            //Set Parse Action Error.
            csv.DefaultParseErrorAction = ParseErrorAction.RaiseEvent;
            csv.SkipEmptyLines = true;             


            int fieldCount = csv.FieldCount;
            string[] headers = csv.GetFieldHeaders();


            //Do the processing of the Data.
            while (csv.ReadNextRecord())
            {
                XElement row = new XElement("KS");
                for (int i = 0; i < fieldCount; i++)
                {
                    XElement rowValue = new XElement("K");
                    XAttribute HeaderName = new XAttribute("N", 
                    headers[i]);
                    XAttribute HeaderValue = new XAttribute("V", csv[i]);
                    rowValue.Add(HeaderName);
                    rowValue.Add(HeaderValue);
                    row.Add(rowValue);
                }
                root.Add(row);
            }
         }
    }  

答案 1 :(得分:0)

如果您不想循环整个数组,请改用find()。它将为您提供更好的性能。

const obj = yourObject

obj.images
   .find(image => image.childFolder)
   .childFolder
   .find(person => person.name == 'Sau')
   .test = "yes"