I need a way to check if a Server already exist inside my JSON Array.
Here is an example JSON Array:
[{
"ID": 14,
"PID": 15728,
"Online": 1,
"Servers": "staging,dev,test"
}, {
"ID": 9,
"PID": 6048,
"Online": 1,
"Servers": ""
}, {
"ID": 8,
"PID": 13060,
"Online": 1,
"Servers": "ubuntu,test"
}, {
"ID": 7,
"PID": 15440,
"Online": 1,
"Servers": "main"
}]
I need a JavaScript function to handle this.
Example calls could be:
checkForDupes("staging") -> true
checkForDupes("debian") -> false
checkForDupes("ubuntu") -> true
checkForDupes("test") -> true
You may use some() and includes() methods or arrays and split() method of string:
let data = [
{"ID": 14, "PID": 15728, "Online": 1, "Servers": "staging,dev,test"},
{"ID": 9, "PID": 6048, "Online": 1, "Servers": ""},
{"ID": 8, "PID": 13060, "Online": 1, "Servers": "ubuntu,test"},
{"ID": 7, "PID": 15440, "Online": 1, "Servers": "main"}
];
function checkForDupes(d, s) {
return d.some(o => o["Servers"].split(",").includes(s));
}
console.log(checkForDupes(data, "staging"));
console.log(checkForDupes(data, "debian"));
console.log(checkForDupes(data, "ubuntu"));
console.log(checkForDupes(data, "test"));
Description:
.some() will run the test function against each object and return true if
any one object passes the test.
.split() will create an array from string of "Servers" property delimited by ,
.includes() will check where the passed name exists in array or not returning true or false as appropriate.
Useful Resources:
Array.prototype.some()
Array.prototype.includes()
String.prototype.split()
Arrow Functions
var checkdupe = function(param) {
var count = [];
for(i=0;i<json.length;i++)
{
if(json[i].Servers.split(',').indexOf(param) != -1)
{
count.push(json[i].ID);
}
}
if(count.length>1){
return true;
}
}
you can use that count array to get more detail
indexOf might be the best choice rather than contains or includes, if it comes to a point where speed matters
Related
I got JSON data, like:
{
"id": 1,
"active": true,
"dependency": [
{ "id": 2 }
{ "id": 3 }
]
},
{
"id": 2,
"active": true
},
{
"id": 3,
"active": true
}
I want to retrieve the "active" value for each dependency in the id 1 object. So far I used a forEach to get those dependency.
thisElement.dependency.forEach(function(id) {
console.log(id)
}
Which returns id 2 and id 3 as objects. Is there a way to use id.active straight away? By using only one loop? Because the result so far are objects without any connection to the related JSON data. Would it require to loop through the whole JSON data to retrieve those values?
The most efficient thing to to is create a hashmap with an Object or Map first so you only need to iterate the array once to find dependency related values.
You could do it by using Array#find() to search whole array each time but that is far more time complexity than the o(1) object lookup
const activeMap = new Map(data.map(obj => [obj.id, obj.active]))
data[0].dependency.forEach(({id}) => console.log(id ,' active: ' , activeMap.get(id)))
<script>
const data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2 },
{"id": 3}
]
},
{
"id": 2,
"active": false
},
{
"id": 3,
"active": true
}
]
</script>
I'm practicing how to maniupulate data in JS in this article: http://learnjsdata.com/combine_data.html
var articles = [
{"id": 1, "name": "vacuum cleaner", "weight": 9.9, "price": 89.9, "brand_id": 2},
{"id": 2, "name": "washing machine", "weight": 540, "price": 230, "brand_id": 1},
{"id": 3, "name": "hair dryer", "weight": 1.2, "price": 24.99, "brand_id": 2},
{"id": 4, "name": "super fast laptop", "weight": 400, "price": 899.9, "brand_id": 3}
];
var brands = [
{"id": 1, "name": "SuperKitchen"},
{"id": 2, "name": "HomeSweetHome"}
];
articles.forEach(function(article) {
var result = brands.filter(function(brand){
return brand.id === article.brand_id;
});
delete article.brand_id;
article.brand = (result[0] !== undefined) ? result[0].name : null;
});
I'm confused with the last part: article.brand = (result[0] !== undefined) ? result[0].name : null;
I understand the conditional operation: it wants to have null value if result[0] is not defined. But I'm wondering what result[0] refers to. I thought it would take first object: {"id":2, "name": "HomeSweetHome"} so there should be for loop to iterate all objects in order to see if objects meet the condition? Could you inform me what I'm missing or/and what result[0] refers to?
Thanks,
result[0] will be undefined in case there is no element in result. result is expected to be an array of brands filtered by the filter operation
The filtered array result will have same brand as that of the current article in the outer foreach loop. The filter condition is going to achieve that.
It looks like in this particular case you will get only one element in result array always as there are unique brand ids. It might have more elements in case of duplicated brand ids.
result[0] points to first element in the array result
So I have an array of object that I want to use for my server, each object has the same amount of keys.
Here is a simplified version of the array:
[{
"BTQ": 1,
"COLLIC": "Foo1",
"MMC": "Bar1",
"PTURE": 39,
"STOCK": 6,
},
{
"BTQ": 1,
"COLLIC": "Foo1",
"MMC": "Bar2"",
"PTURE": 31,
"STOCK": 2,
},
{
"BTQ": 2,
"COLLIC": "Something1",
"MMC": "AnotherThing1",
"PTURE": 40,
"STOCK": 5,
},
{
"BTQ": 2,
"COLLIC": "Something1",
"MMC": "AnotherThing1",
"PTURE": 11,
"STOCK": 7,
}]
and I want to build a function that loops through all of these objects, and builds another JSON array that looks like that:
[
{
"BTQ": 1,
"COLLICs": {
"Foo1": {
"Bar1": {
"Stock": 6,
"PTURE" {"39": 6}
},
"Bar2": {
"Stock": 2,
"PTURE": {"31": 2,}
}
}
}
},
{
"BTQ": 2,
"COLLICs": {
"Something1": {
"AnotherThing1": {
"Stock": 12,
"PTURE": {"40": 5, "11": 7}
}
}
}
},
//etc ...
]
I am using NodeJS, and I figured out I needed to build a function like this one :
function step(i){
if (i < raw.length){
data.push(raw[i].A);
step(i + 1);
} else {
console.log("Finished");
console.log(data);
}
}
but the thing is I don't know how to nest this function...
Here is what I want to achieve in the end:
1) Loop through each object in the raw array (done with the function above)
2) For each object, loop through data (the sorted array) and see if any of the objects in there has the same "BTQ" value, if so : go into the object, and see if the raw[i].COLLIC exists the data[j].COOLLICs' keys. If exists, look if the MMC exists, ETC ... If any of the values does not exist, create a new key/object which stores all the informations, and then start again with the following raw object.
It is probably not very clear and I'm sorry for that, if it can help, I had built the same algorithm but with for loops, I can paste it here if it could help to make things clearer.
I really hope you can help me because I'm loosing my mind on this ...
Thanks ! Ali
I create an object from duplicates array and I dynamically push to it elements. Everything works fine, excepting that I'm getting an additional empty element and I can't figure it out why...
This is my code:
for(i=0;i<duplicates.length; i++) {
Logger.log(duplicates[i]);
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
for(var j in duplicates[i].variable) {
request.rules[0].tags[0].variables.push({
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
});
}
}
Here is an example:
duplicates = [
{scopeDef=.*, scope=Global 4, variable=[trackingcode, v1, v2]}, {scopeDef=https://www.delta.com/, scope=Homepage 2, variable=[v4, v5, v6, v7]},
]
After I execute the code I get the following log:
First object
{name=Global 4, rules=[{name=Global 4 OP SDR Sync, tags=[{variables=[
{},
{matchType=Regex, variable=trackingcode, value=.*},
{matchType=Regex, variable=v1, value=.*},
{matchType=Regex, variable=v2, value=.*}], condition=false, tagId=1.0}, {condition=false, tagId=1.0}], ruleSetId=3.0}], id=3.0}
Second object
name=Homepage 2, rules=[{name=Homepage 2 OP SDR Sync, tags=[{variables=[
{},
{matchType=Regex, variable=v4, value=https://www.delta.com/},
{matchType=Regex, variable=v5, value=https://www.delta.com/},
{matchType=Regex, variable=v6, value=https://www.delta.com/},
{matchType=Regex, variable=v7, value=https://www.delta.com/}], condition=false, tagId=1.0}, {condition=false, tagId=1.0}], ruleSetId=3.0}], id=3.0}
Note that both objects contain an empty element...why is that element added and how can I get rid of it??
You defined that empty object here:
"variables":[
{
}
],
Change your code as below to fix this :
Current :
"variables":[{}],
To Fix :
"variables":[],
I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle