javascript - Check if an object exists with a property set to a particular value in a nested object (array of objects) -
I am trying to create a JSON object from a data source that should look something like this:
< {"Name": {"name": "cabbage", "type": "vegetable"}, {"name": "pot", "type": "vegetable"}, {"name": "carrot" , "Type": "fruit"}, {"name": "apple", "type": "fruit"}, {"name": "orange", "type": "fruit"}]As I have worked through a data source, I have a nested object named 'allProduce' with related entries Want to add Bjekt are if and only if the object does not already exist.
So if I have the following lines in my data source:
** Type of product is in the original stock of the country? * Apple Fruit Ireland Yes apple fruit France Yes apple fruit USA no cabbage vegetable UK cabbage cauliflower vegetable France
Then all 'project' should be nested object as a result:
/ Pre>This is the place where I am confusing because I'm not sure how every time I (without looping through the whole nested object ) Check whether the record is present or not. I am doing something like this (using jQuery:
$ ('source data test table T'). (I, line) {var fatal = $. Trim ($ (line) .find ('td: nth-child (1)'). Text ()) var type = $ .trim ($ (line) Find ('td: nth-child (2)'). Text ();) (If there is no item already present with the object set with "NAME" property) {allProduce.push ({"name ": Furname," Type ": Type});}});
If statement bracket Should be in, where I currently have ("NAME" with the name of a commodity object with the property that does not already exist) . Maybe there's a better way to do this?
You can use jQuery's
filter ()
method:$ ('sourceData table tbody tr'). Each (function (i, line) {var fruit name = $ .trim ($ (line) .find ('td: text ()) .text ()) var type = $ .trim ($ (line) .find ('Td: nth-child (2)'). Text ()); if ($ (allProduce)) .filter (function (index, object) {re-turn object.name == fnn;}). Length == 0) {allProduce.push ({"name": fame, "type": type}); }});
Comments
Post a Comment