Empty element is added to Object - javascript

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":[],

Related

How to get JSON entry from returned objects

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>

Dynamically add array elements to JSON Object

I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my problem...
for(i=0;i<duplicates.length; i++) {
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
I take object properties from the duplicates array that can have the following elements:
[{scopeDef=.*, scope=Global, variable=[trackingcode, v1, v2]}, {scopeDef=^https?://([^/:\?]*\.)?delta.com/products, scope=Products Section, variable=[v3]}]
As you can see, an object contain variable element that can have multiple values. I need to push to the JSON object all those values dynamically (meaning that there could be more than 3 values in an array).
For example, after I push all the values from the duplicates array, my JSON object should look like this:
name=Products Section,
rules=
[
{
name=Products Section OP SDR Sync,
tags=[
{
variables=
[
{
matchType=Regex,
variable=v3,
value=^https?://([^/:\?]*\.)?delta.com/products
},
{
matchType=Regex,
variable=trackingcode,
value=.*
},
{
matchType=Regex,
variable=v1,
value=.*
},
{
matchType=Regex,
variable=v2,
value=.*
}
],
condition=false,
},
{
condition=false,
tagId=1
}
],
ruleSetId=3
}
]
}
I tried the following code but without success:
for(var j in duplicates[i].variable) {
var append = JSON.parse(request);
append['variables'].push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
}
Please let me know if I need to provide additional information, I just started working with JSON objects.
First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:
var json='{"a":"1", "b":"2"}';
var x = JSON.parse(json);
Next, you have any property of object wrapped in arrays. To correctly work with it you should write:
request.rules[0].tags[0].variables.push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
If you want to use your code snippet, you need some changes in request:
var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
To understand JSON remember basic rule: read JSON backward. It means:
property
object.property
arrayOfObfects['id'].object.property
mainObject.arrayOfObfects['id'].object.property
and so on. Good luck!

elasticsearch autosuggest returning tricky JSON

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

How merge two objects array in angularjs?

I want to append following object array with existing one in angulajs for implementing load more feature.
ie,appending AJAX response with existing one each time.
I have one variable, $scope.actions which contains following JSON data,
{
"total": 13,
"per_page": 2,
"current_page": 1,
"last_page": 7,
"next_page_url": "http://invoice.local/activities/?page=2",
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I want to append following JSON response each time this variable.
{
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I have tried with $scope.actions.data.concat(data.data);
but it is not working and getting following error message
$scope.actions.data.concat is not a function
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1

How do I chain "SelectMany" calls with linqjs (or flatten JSON)

Using linq.js how can I chain two SelectMany calls together.
Given the following JSON structure:
[
{
"UpFrontCost": "29.95",
"Currency": "USDAUD",
"FittingDate": "2013-07-08 06:30:16Z",
"Widgets": [
{
"ID": 3,
"Name": "Test1"
},
{
"ID": 4,
"Name": "Test19"
},
{
"ID": 6,
"Name": "Test8"
}
]
},
{
"UpFrontCost": "29.95",
"Currency": "USDAUD",
"FittingDate": "2013-07-08 06:30:16Z",
"Widgets": [
{
"ID": 67,
"Name": "Test1"
},
{
"ID": 99,
"Name": "Test19"
},
{
"ID": 34,
"Name": "Test8"
}
]
}
]
I would like a list of all the "Widgets" (in this example a list of 6 widgets).
You don't need to really chain anything. Your root object is an array, you just want to select each widget for each object in that array.
var query = Enumerable.From(jsonObject)
.SelectMany("$.Widgets") // Select each widget found in the Widgets property
.ToArray();
To flatten that array of widgets attaching each property of the parent object to the result, there's a couple of ways you could do it. You can use a nested query using the function syntax.
var query = Enumerable.From(jsonObject)
.SelectMany(function (item) {
return Enumerable.From(item.Widgets)
.Select(function (widget) {
return {
ID: widget.ID,
Name: widget.Name,
UpFrontCost: item.UpFrontCost,
Currency: item.Currency,
FittingDate: item.FittingDate
};
});
})
.ToArray();
Or using the lambda string syntax:
var query = Enumerable.From(items)
.SelectMany("$.Widgets",
// argument 1 ($) - the parent object
// argument 2 ($$) - the selected object (a widget)
"{ ID: $$.ID, Name: $$.Name, UpFrontCost: $.UpFrontCost, Currency: $.Currency, FittingDate: $.FittingDate }"
)
.ToArray();

Categories

Resources