简体   繁体   English

通过查找值AngularJS在数组中添加键

[英]Adding key in an array by finding a value AngularJS

I am trying to add an extra key in a JSON array by searching any key value. 我正在尝试通过搜索任何键值在JSON数组中添加一个额外的键。

Example JSON:- JSON示例:-

[
  {
    "$id": "2025",
    "ID": 41,
    "Name": "APPLE"
  },
  {
    "$id": "2026",
    "ID": 45,
    "Name": "MANGO"
  },
  {
    "$id": "2027",
    "ID": 48,
    "Name": "GUAVA"
  }
]

Suppose I have to add a new key pair example "Price": 50 after "Name": "MANGO" or by finding ID ID": 45 . So my expected new JSON will be :- 假设我必须在"Name": "MANGO"或通过找到ID ID": 45之后添加一个新的密钥对示例"Price": 50 。因此,我期望的新JSON将是:-

[
  {
    "$id": "2025",
    "ID": 41,
    "Name": "APPLE"
  },
  {
    "$id": "2026",
    "ID": 45,
    "Name": "MANGO",
    "Price": 50
  },
  {
    "$id": "2027",
    "ID": 48,
    "Name": "GUAVA"
  }
]

It must add on the object related to matched search key. 它必须添加与匹配的搜索关键字相关的对象。

So, I am not able to find out any function related to the issue. 因此,我无法找到与此问题相关的任何功能。

You can run a loop and check the condition and then add a property to an object. 您可以运行循环并检查条件,然后将属性添加到对象。 Here is a running code snippet. 这是一个正在运行的代码片段。 You can read here more about JavaScript Objects 您可以在此处阅读有关JavaScript对象的更多信息

 var myarray = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ] for(var i=0;i<myarray.length;i++){ if(myarray[i].$id === "2025" || myarray[i].Name === "APPLE"){ var data = myarray[i]; data.price = 50 } } console.log(myarray) 

You can use array#find to compare the ID . 您可以使用array#find比较ID Then based that you can add Price key to the object. 然后根据该Price可以向对象添加Price键。

 let arr = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ], id = 45, obj = arr.find(({ID}) => ID === id); if(obj); obj.Price = 50; console.log(arr); 

You can try with: 您可以尝试:

data.find(item => item.ID === 45).price = 50;

To cover the case if item is not available: 要解决此问题(如果该项目不可用):

(data.find(item => item.ID === 45) || {}).price = 50;   

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

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