How merge two objects array in angularjs? - javascript

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

Related

Is there a way to read <script> tag contents

I have a site in which there is a <script> with a JSON inside. With user script in Tampermonkey, I want to get that JSON to work with it later.
So I thought that I can get it with getElemntsByTagName("script"), but I couldn't figure out how to get string out of it.
How do you get a string from getElemntsByTagName("script"), like console.log does?
Is there an easier way to do so?
window.wpProQuizInitList = window.wpProQuizInitList || [];
window.wpProQuizInitList.push({
id: '#wpProQuiz_67',
init: {
quizId: 67,
mode: 2,
globalPoints: 76,
timelimit: 0,
resultsGrade: [0],
bo: 3,
qpp: 0,
catPoints: [76],
formPos: 0,
lbn: "\u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u0438 \u0442\u0435\u0441\u0442",
json: {
"2944": {
"type": "single",
"id": 2944,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
"2945": {
"type": "single",
"id": 2945,
"catId": 0,
"points": 1,
"correct": [0,1,0,0]
},
"2946": {
"type": "single",
"id": 2946,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
…
}
}
}
You can use document.querySelector to get the first <script> element; there is no need to obtain a live HTMLCollection to get one element. You can then read its textContent.
let value = document.querySelector('script').textContent;
getElementsByTagName("script") will return an HTMLCollection which contains a list of script tags. You can get the text of the first script tag like this:
getElementsByTagName("script")[0].innerText

Display json response in ajax jquery,

The JSON Response I'm getting,
{
"user_data": {
"id": 22,
"first_name": xxx,
"last_name": xxx,
"phone_number": "123456789",
},
"question_with_answers" : [
{
"id": 1,
"question_name": "Features of our project that you like (select one
or more):",
"answers": [
{
"id": 19,
"question_id": 1,
"customer_id": 22,
"option": "Location",
},
{
"id": 20,
"question_id": 1,
"customer_id": 22,
"option": "Architecture",
},
]
},
{
"id": 2,
"question_name": "Features of our project that you DID NOT like
(select one or more):",
"answers": [
{
"id": 22,
"question_id": 2,
"customer_id": 22,
"option": "Location",
},
]
},
{
"id": 3,
"question_name": "How soon are you looking to buy a new home?",
"answers": [
{
"id": 24,
"question_id": 3,
"customer_id": 22,
"option": "Immediately",
}
]
}
]
}
So that is how JSON response looks like, now I need to display data using jquery
My js code
function openModal(Id){
var CustomerId = Id;
$.ajax({
type : 'get',
url: 'customer-details',
data: {
'CustomerId':CustomerId
},
success: function(data)
{
//what I have to do here
}
})
}
The output I want is,
first_name : xxx
last_name : xxx
phone_number : 123456789
1.Features of our project that you like (select one or more):
ans: Location, Architecture
2.Features of our project that you DID NOT like (select one or more)
ans: Location
3.How soon are you looking to buy a new home?
ans: Immediately
Thats how my output should look like from above json response,Is it possible to get above output using that Json response I got
There are two variable that I have passed from backend like user_data and question_with_answers
In success handler first of all make your json into a array using
var obj = JSON.parse(data);
Now in data you have array of your response and you can use this like
obj.first_name
obj.last_name
Note:- may be you have issue in JSON.parse so use first
var data = json.stringify(data)
after that use Json.parse function and use above data variable
this data
You have to set the dataType in the $.ajax call, set it to dataType:"json"...
After that, you got on the data variable in the success the json object and you can access it like data.user_data or data.id or data.first_name.
If you dont define the json as dataType, it will not work properly.
Addition
If you want to display the content of "question_with_answer" you have to iterate trough it, like ....
for (i in data.question_with_answer) { alert(data.qestion_with_answer[i]); }

Empty element is added to Object

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

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

Categories

Resources