find length of json name/values pairs - javascript

In this code I'm using the 2 name/values pairs in each record
I'm getting the alert with value 4 while I want to search the of numbers of pairs we have that is FirstName,sal so I want the value 2 in alert????
var Newdata = [
{ "FirstName" : "John" , "Sal" : 10 },
{ "FirstName" : "Anna" , "Sal" : 30 },
{ "FirstName" : "Peter" , "Sal" : 30 },
{ "FirstName" : "Hemant" , "Sal" : 30 },];
alert(Newdata.length);

Try to use Object.keys() like,
alert(Object.keys(Newdata[0]).length);
Demo

Related

array in array filter - javascript

hello i need help with array , as you can see my data
{
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
I can access elements such as id , title or logo because they are not arrays.
How can I loop through the data inside the array since there is an array in the category in yield?
var data = this.database.filter((item) => item.type == searchType)
var data = this.database.filter((item) => item.category == searchCategory)
It's okay because my type value doesn't have an array.
But when I enter my category value, it only gets the first index[0]. It does not look at other indexes.
in summary,
item.category[0] , item.category[1] , item.category[2]...........
How can I get index browsing like
if your data looks like this :
let data ={
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
and if we have array of data you can do something like this :
myArray.filter(item=>item.category.indexOf(searchCategory)>=0)
but if you want to explore in object rather than array you can do this :
data.category.indexOf(searchCategory)>=0
You could make this a bit generic, by testing whether the targeted field is an array, using Array.isArray, and then call a filter on each element, and see if any is positive (using .some()). The filter can be function that is provided, so that it can perform a simple match, or apply a regular expression, or anything else.
Instead of testing with Array.isArray you could skip that step and check whether the value has a .some() method. If so, calling it will give the desired outcome, and otherwise (using the .? and ?? operators), the filter should be applied to the value as a whole:
Here is how that looks:
function applyFilter(data, field, filter) {
return data.filter(item => item[field]?.some(filter) ?? filter(item));
}
// Example use:
var data = [{
"category" : [ "Action", "Thriller", "Horror"],
"type" : "Series",
}, {
"category" : [ "Historical", "Romance" ],
"type" : "Theatre",
}];
// Find entries that have a category that looks like "roman*":
var result = applyFilter(data, "category", value => /^roman.*/i.test(value));
console.log(result);
If you are running on an older version of JavaScript, and don't have support for .? or ??, then use:
return data.filter(item => Array.isArray(item[field])
? item[field].some(filter)
: filter(item));

Modify existing json file using nodejs

I have a json file named a1.json->(It has the following structure)
{ "Key1" :
[ {
"Key11" : "Value11" ,
"Key12" : "Value12"
},
{
"Key21" : "Value21" ,
"Key22" : "Value22"
}
]
}
I am iterating through a data file which has certain values. If the values match i will have to add an extra key to that particular dictionary only. For example-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1"
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
I want to add a key value pair in that list whose key value "a" is "A1". So the final result will look something like this-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1" ,
"New_Key_Array" :
[
{
"Found" : "yes",
"Correctness" : "true"
}
]
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
How do I go about this. I am a bit new to JSON formatting and still learning how to edit existing JSON files?
You can use JSON.parse() to parse your json file/string into a JavaScript object. In your example:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
To add a new key to your object, it's possible with native JavaScript code, if that's what you want:
j.Key1[0]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
To convert back into json formatted string, you can use the JSON.stringify() function.
I am providing a code snippet for your problem:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
console.log("JSON at the beginning:\n", j);
j.Key1.forEach((element, index) =>{
if(element.a === "A1"){
//Here I have to edit the JSON obj
j.Key1[index]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
}
});
console.log("JSON edited:\n ",j);
let objString =JSON.stringify(j);

Find nested property from ember lodash and pick the value

I am new to javascript.
I would like to check whether the specific nested property is present or not in an array of items, ex)
[{
"_id" : ObjectId("5c4ec057e21b840001968d31"),
"status" : "ACTIVE",
"customerId" : "sample-book",
"bookInfo" : {
"bookChunks" : [
{
"key" : "Name",
"value" : "test"
},
{
"key" : "Surname1",
"value" : "testtt"
},
{
"key" : "user-contact",
"value" : "sample-value",
"ContactList" : {
"id" : "sample-id",
"timeStamp" : "Tue, 20 Sep 2016 07:49:25 +0000",
"contacts" : [
{
"id" : "contact-id1",
"name" : "Max Muller",
"phone_number" : "+XXXXXXX"
},
{
"id" : "contact-id2",
"name" : "Max Muller",
"phone_number" : "+XXXXXXX"
}
]
}
}
]
}
},
{
"_id" : ObjectId("5c4ec057e21b840001968d32"),
"status" : "ACTIVE",
"customerId" : "sample-book1",
"bookInfo" : {
"bookChunks" : [
{
"key" : "Name",
"value" : "test"
},
{
"key" : "Surname1",
"value" : "testtt"
}
]
}
}]
Here, I would like to find whether any item has ContactList or contacts present. If it is present take the item and put it in a separate list.
I am using ember-lodash. Using normal javascript or lodash would be fine for me. Any help will be really appreciated.
You could use filter and some. This returns all the objects which have at least one object with ContactList property inside bookInfo.bookChunks array.
const input=[{"_id":"5c4ec057e21b840001968d31","status":"ACTIVE","customerId":"sample-book","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"},{"key":"user-contact","value":"sample-value","ContactList":{"id":"sample-id","timeStamp":"Tue, 20 Sep 2016 07:49:25 +0000","contacts":[{"id":"contact-id1","name":"Max Muller","phone_number":"+XXXXXXX"},{"id":"contact-id2","name":"Max Muller","phone_number":"+XXXXXXX"}]}}]}},{"_id":"5c4ec057e21b840001968d32","status":"ACTIVE","customerId":"sample-book1","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"}]}}]
const output = input.filter(o =>
o.bookInfo.bookChunks.some(c => "ContactList" in c)
)
console.log(output)
If you just want to check if any of the objects have ContactList, you could replace filter with another some
(Note: This assumes that bookInfo.bookChunks will not be undefined. Otherwise you'd have to add a undefined check before using the nested property)

If condition does not work / not running

I'm trying to match mongodb object id with if condition:
if (reply[i].data[j].ref == item._id) console.log('match!!!')
The sample of reply & item:
// REPLY
[{
"_id":10,
"data": [
{
"_id":"57f485203858fe43b464ae52",
"type":"product",
"ref":"57f485473858fe43b464ae56",
"name":"KARUNG",
"direction":"in",
"supplier":null,
"information":"PENYESUAIAN JUMLAH",
"qty":200,
"manifest":null,
"timestamp":"2016-10-05T04:44:16.354Z",
"saldo":1200
}
]
}]
// ITEM
{
"_id" : "57f485473858fe43b464ae56",
"name" : "BERAS KC",
"unit" : "SAK",
"qty" : 213,
"weight" : 10
}
I was also trying to convert both to ObjectId using mongojs.ObjectId, but it doesn't work.
The full code snippet: http://pastebin.com/SYTLVWqT

How to query neighbor elements in MongoDB?

I am implementing a ranking system. I have a collection with elements like this:
{"_id" : 1, "count" : 32}
{"_id" : 2, "count" : 12}
{"_id" : 3, "count" : 34}
{"_id" : 4, "count" : 9}
{"_id" : 5, "count" : 77}
{"_id" : 6, "count" : 20}
I want to write a query that return an element which has {"id" : 1} and 2 other neighbor elements (after sorting by count). Totally 3 elements returned.
Ex:
After sorting:
9 12 20 32 34 77
The query should return 20 32 34.
You will never get this in a single query operation, but it can be obtained with "three" queries. The first to obtain the value for "count" from the desired element, and the subsequent ones to find the "preceding" and "following" values.
var result = [];
var obj = db.collection.findOne({ "_id": 1 }); // returns object as selected
result.push(obj);
// Preceding
result.unshift(db.collection.findOne({
"$query": { "count": { "$lt": obj.count } },
"$orderby": { "count": -1 }
}));
// Following
result.push(db.collection.findOne({
"$query": { "count": { "$gt": obj.count } },
"$orderby": { "count": 1 }
}));
Asking to do this in a "single query" is essentially asking for a "join", which is something that MongoDB essentially does not do. It is a "Set Intersection" of the discrete results, and that in SQL is basically a "join" operation.

Categories

Resources