How to add attributes to JSON array using javascripts? - javascript

I want to construct following JSON dynamically using Javascript.
{
"Events": [{
"Name": "Code Change",
"Enabled": "true",
"Properties": [{
"Name": "url",
"Value": "val"
}]
}],
"Properties": [{
"Name": "url",
"Value": "val"
}]
}
So i wrote following code but it creates JSON object where Name, Enabled and properties under separate curly brackets. Is there anyway to resolve this issue instead of using push method?
Code
var eventProperties="[{'Name':'url','Value':'val'}]";
var subscriptionProperties="[{'Name':'url','Value':'val'}]";
var eventArray = JSON.parse('[1, 5, "false"]');
var subArray = JSON.parse('[1, 5, "false"]');
var subscription = {
Events: [],
Properties: []
};
if(eventName != null && eventName != "") {
subscription.Events.push({
"Name" : eventName
});
}
var index = 0;
if(eventEnabled != null && eventEnabled != "") {
subscription.Events.push({
Enabled: eventEnabled
});
}
if(eventProperties != null && eventProperties != "") {
subscription.Events.push({
"Properties": eval('(' + eventProperties + ')')
});
}
if(subscriptionProperties != null && subscriptionProperties != "") {
subscription.Properties = eval('(' + subscriptionProperties + ')');
}
Output given
{
"Events": [{
"Name": "Code Change"
},
{
"Enabled": "true"
},
{
"Properties": [{
"Name": "url",
"Value": "val"
}]
}],
"Properties": [{
"Name": "url",
"Value": "val"
}]
}

Yes there is. You need to create only one object like so.
subscription.Events.push({
Name: eventName,
Enabled: eventEnabled,
Properties: JSON.parse(eventProperties)
});
Or using the current flow you have:
var subscription = {};
var eventObject = {};
if(eventName != null && eventName != "") {
eventObject.Name = eventName;
}
if(eventEnabled != null && eventEnabled != "") {
eventObject.Enabled = eventEnabled;
}
if(eventProperties != null && eventProperties != "") {
eventObject.Properties = JSON.parse(eventProperties);
}
subscription.Events = [eventObject];
if(subscriptionProperties != null && subscriptionProperties != "") {
subscription.Properties = JSON.parse(subscriptionProperties);
}

Related

Angular - Search for multiple keys inside array of objects

The array of objects:
array = [
{
"id": 1,
"key": "key1",
"name": "name1",
"area": "area1",
"functionalArea": "func1",
"lob": "lob1",
},
{
"id": 2,
"key": "key2",
"name": "name2",
"area": "ALL",
"functionalArea": "ALL",
"lob": "ALL",
},
]
My atempt:
const { name, id, functionalArea, area, lob } = this.form.getRawValue();
const searchTerms = {
widgetName,
widgetId,
functionalArea,
area,
lob,
};
.subscribe(
(res) => {
let results = array.filter((item) =>
searchTerms.functionalArea === 'ALL' &&
searchTerms.area === 'ALL' &&
searchTerms.lob === 'ALL' &&
!searchTerms.id &&
!searchTerms.name
? item
: item.key.toLowerCase().includes(searchTerms.widgetId.toLowerCase()) ||
item.name.toLowerCase().includes(searchTerms.widgetName.toLowerCase()) ||
(item.functionalArea.toLowerCase().includes(searchTerms.functionalArea.toLowerCase()) &&
item.area.toLowerCase().includes(searchTerms.area.toLowerCase()) &&
item.lob.toLowerCase().includes(searchTerms.lob.toLowerCase()))
);
},
The problem:
I cannot filter for multiple conditions using includes() function, it does not work.
If i remove all conditions and use only one than the includes() function works.
A filter is a function that return true or false, As always you want to "search" is good at first convert to upperCase (or lowerCase) the "condition"
searchTerms.functionalArea=searchTerms.functionalArea?
searchTerms.functionalArea.toLowerCase():'ALL'
searchTerms.area =searchTerms.functionalArea?
searchTerms.area.toLowerCase():'ALL'
searchTerms.lob =searchTerms.functionalArea?
searchTerms.lob.toLowerCase():'ALL'
searchTerms.name=searchTerms.name?
searchTerms.name.toLowerCase():'ALL'
const result=array.filter((item)=>{ //<--see this bracket
let result=searchTerms.functionalArea=='ALL' ||
searchTerms.functionalArea.includes(item.functionalArea.toLowerCase());
result=result && (searchTerms.area =='ALL' ||
searchTerms.area.includes(item.area .toLowerCase());)
result=result && (searchTerms.lob =='ALL' ||
searchTerms.lob.includes(item.lob .toLowerCase());)
//Update
result=result && (!searchTerms.widgetId ||
searchTerms.widgetId==item.id)
result=result && (!searchTerms.widgetName ||
searchTerms.widgetName.includes(item.name.toLowerCase());)
return result; //<--as you use bracket, you should use return
})
You have to filter only if the conditions about searchTerm are true, something like this:
let results = (searchTerms.functionalArea === 'ALL' &&
searchTerms.area === 'ALL' &&
searchTerms.lob === 'ALL' &&
!searchTerms.id &&
!searchTerms.name)
? array
: array.filter((item) => item.key.toLowerCase().includes(searchTerms.widgetId.toLowerCase()) ||
item.name.toLowerCase().includes(searchTerms.widgetName.toLowerCase()) ||
(item.functionalArea.toLowerCase().includes(searchTerms.functionalArea.toLowerCase()) &&
item.area.toLowerCase().includes(searchTerms.area.toLowerCase()) &&
item.lob.toLowerCase().includes(searchTerms.lob.toLowerCase())));
EXAMPLE (check the console output): https://stackblitz.com/edit/typescript-y2w6sr?file=index.ts

How to add and remove values from local storage on checkbox click in Angular8

i have dynamic generated list of checkbox, i want to create array with objects.
I wanted to push data in array of objects if value is true and setItem to localStorage,
and if value is false then it will remove objects from local storage
Can anyone help me to optmize my code with expected output.
Expected output
[
{
"key": "Test",
"value": true
},
{
"key": "Test1",
"value": true
},
{
"key": "removeItem",
"value": false
}
]
Code
setColumn($event, item) {
var obj = {}, valueAliasPair = [];
if (item.tabelHeader.data != '' && $event.checked === true) {
obj['key'] = item.tabelHeader.data;
obj['value'] = $event.checked;
valueAliasPair.push(obj);
localStorage.setItem('AvailableAmt', JSON.stringify(valueAliasPair));
}
if (item.tabelHeader.data != '' && $event.checked === false) {
localStorage.removeItem('AvailableAmt', obj['key']);
}
console.log(valueAliasPair, "valueAliasPair");
}
Updated:
setColumn($event, item) {
let valueAliasPair = JSON.parse(localStorage.getItem("AvailableAmt") || "[]");
if (item.tabelHeader.data != "") {
if ($event.checked) {
valueAliasPair.push({
key: item.tabelHeader.data,
value: true,
});
localStorage.setItem("AvailableAmt", JSON.stringify(valueAliasPair));
} else {
const ind = valueAliasPair.findIndex((x) => x.key === item.tabelHeader.data);
valueAliasPair.splice(ind, 1);
localStorage.setItem("AvailableAmt", JSON.stringify(valueAliasPair));
}
}
console.log(valueAliasPair, "valueAliasPair");
}

Remove an object from array

am trying to remove an object from an Array list within a JavaScript object.
The Structure if the Object:
{
"temp": {
"name": "",
"css": {
"bg_color_main": "#xxxxx",
"part_bg_color": "xxxxx",
"txt_font_family": "xxxxxxxx",
"txt_font_color_main": "#xxxxx",
"headline_font_family": "xxxxx",
},
"part": [
{
"name": "xxxxxx",
"style": {}
},
{
"name": "yyyyyy",
"style": {}
},
{
"name": "zzzzzz",
"style": {}
}
]
}
}
The Code:
$.each(jsonData.temp.part, function(k, v) {
var tt = this; //var tt = $(this)
if( v.name === partName ){
delete tt[k];
}
});
Nothing happens.. no error, no warning!
There are two problems in your code. First, delete does not remove elements. It only sets them to undefined. Use splice instead.
Second, it never gets to do that, because tt (or this) is the object inside the array that you are currently working on, not the array you are iterating. You need to access the array explicitly with its full name.
$.each(jsonData.temp.part, function(k, v) {
var tt = this; //var tt = $(this)
if( v.name === partName ){
jsonData.temp.part.splice(k,1);
}
});
Alternatively you could simply use a filter.
var o = {
"temp": {
"name": "",
"css": {
"bg_color_main": "#xxxxx",
"part_bg_color": "xxxxx",
"txt_font_family": "xxxxxxxx",
"txt_font_color_main": "#xxxxx",
"headline_font_family": "xxxxx",
},
"part": [
{
"name": "xxxxxx",
"style": {}
},
{
"name": "yyyyyy",
"style": {}
},
{
"name": "zzzzzz",
"style": {}
}
]
}
}
o.temp.part = o.temp.part.filter(function (element) {return element.name !== "zzzzzz"});
You could use different approach, for example:
If the reference of the array is not needed, you can use reduce to create a new array:
jsonData.temp.part = jsonData.temp.part.reduce(function(acc, value) {
if( value.name !== partName ){
acc.push(value);
}
return acc;
}, []);
Also you can find the index of the element, and use splice to mantain the reference:
var indexElement = jsonData.temp.part.reduce(function(acc, value, index) {
if( value.name !== partName ){
return index;
}
return acc;
}, -1);
jsonData.temp.part.splice(indexElement, 1)
Both ways work.
Here is a possible solution:
The simplest way is to use delete.
var jsonData = {
"temp": {
"name": "",
"css": {
"bg_color_main": "#xxxxx",
"part_bg_color": "xxxxx",
"txt_font_family": "xxxxxxxx",
"txt_font_color_main": "#xxxxx",
"headline_font_family": "xxxxx",
},
"part": [
{
"name": "xxxxxx",
"style": {}
},
{
"name": "yyyyyy",
"style": {}
},
{
"name": "zzzzzz",
"style": {}
}
]
}
}
var nameToRemove = 'xxxxxx';
var parts = jsonData.temp.part;
$.each(parts, function(k, v) {
if (v.name === nameToRemove)
{
delete parts[k];
}
});
//this code is added to just show the result
$.each(parts, function(i, r){
if (r != undefined)
{
$('#result').append(r.name + ',')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="result"></label>
You created a copy and delete item from the copy.
$.each(jsonData.temp.part, function(k, v) {
var tt = this; // now you created a new array!!!
if( v.name === partName ){
delete tt[k]; // here you delete the item from the copy array
delete this[k]; // you remove item from the original array
}
});

JSON.stringify different from direct access to object property, strongloop

I use strongloop to build my api.
On a particular route the query includes model's relations. I get an array of objects that I would like to arrange.
In this particular arranging function I face the following problem.
The function receive an object named "item" containing a "trans" field (this field is an array of another object).
this piece of code :
console.log(JSON.stringify(item, null, 2));
produces this result :
{
"id": 1,
"created": "2015-08-19T21:04:16.000Z",
"updated": null,
"authorid": 0,
"likes": 0,
"shares": 0,
"fav": 0,
"validated": 0,
"comments": 0,
"trans": [
{
"text": "Première question en français",
"questionId": 1
}
],
"answers": [
{
"id": 1,
"questionid": 1,
"questionId": 1,
"trans": [
{
"text": "q1 : reponse 1 en francais",
"answerId": 1
}
]
},
{
"id": 2,
"questionid": 1,
"questionId": 1,
"trans": [
{
"text": "q1 : reponse 2 en francais",
"answerId": 2
}
]
}
]
}
This problem is when I try to reach this part :
item.trans[0].text
console says "item.trans is undifined" and when I try this piece of code :
console.log(item.trans);
I have this result :
function (condOrRefresh, options, cb) {
if (arguments.length === 0) {
if (typeof f.value === 'function') {
return f.value(self);
} else if (self.__cachedRelations) {
return self.__cachedRelations[name];
}
} else {
if (typeof condOrRefresh === 'function'
&& options === undefined && cb === undefined) {
// customer.orders(cb)
cb = condOrRefresh;
options = {};
condOrRefresh = undefined;
} else if (typeof options === 'function' && cb === undefined) {
// customer.orders(condOrRefresh, cb);
cb = options;
options = {};
}
options = options || {}
// Check if there is a through model
// see https://github.com/strongloop/loopback/issues/1076
if (f._scope.collect &&
condOrRefresh !== null && typeof condOrRefresh === 'object') {
//extract the paging filters to the through model
['limit','offset','skip','order'].forEach(function(pagerFilter){
if(typeof(condOrRefresh[pagerFilter]) !== 'undefined'){
f._scope[pagerFilter] = condOrRefresh[pagerFilter];
delete condOrRefresh[pagerFilter];
}
});
// Adjust the include so that the condition will be applied to
// the target model
f._scope.include = {
relation: f._scope.collect,
scope: condOrRefresh
};
condOrRefresh = {};
}
return definition.related(self, f._scope, condOrRefresh, options, cb);
}
}
How can I simply access the "trans" property in this case to get the text inside ?
(Not really at easy in js)
Thanks in advance.
It's possible that your item object has implemented the toJSON function.
Pop open your browser's console and run this snippet to see an example of how this can make a difference between the stringified JSON and the actual object:
var x = {
name: "foo",
children : function() {
return [ { name: 'child 1' }, { name: 'child 2' } ];
},
toJSON: function() {
var simplified = { name: this.name, children: this.children() };
return simplified
}
};
// shows children as a simple array
console.log( JSON.stringify( x, null, 2 ) );
// {
// "name": "foo",
// "children": [
// {
// "name": "child 1"
// },
// {
// "name": "child 2"
// }
// ]
// }
// oops... not what you expected
console.log( x.children[0].name );
// Uncaught TypeError: Cannot read property 'name' of undefined
Of course, the easiest fix would be to parse the stringify result:
var y = JSON.parse( JSON.stringify( x ) );
console.log( y.children[0].name );
It's a last-case-scenario-type solution, though, since JSON.stringify is a very expensive function.

Remove objects/fields which contains a specific word

I have a JSON file; I want to remove all of the fields or objects, whose names are a specific word (lets say "test") and then return the stripped JSON file back; how can I do it in Node.JS?
Here is an example of my JSON file:
{
"name": "name1",
"version": "0.0.1",
"storage": {
"db": {
"test": "STRING",
"tets2": "STRING",
},
"test": {
"test11": "STRING",
"test2": {
"test3": "0",
"test4": "0"
},
"test5": {
"test6": "0",
"test7": "0"
}
},
"test8": {
"test9": "STRING",
"test10": "STRING"
}
}
}
The desired output:
{
"name": "name1",
"version": "0.0.1",
"storage": {
"db": {
"tets2": "STRING",
},
"test8": {
"test9": "STRING",
"test10": "STRING"
}
}
}
I tried the folloiwng, but I dont know how to use typeof() and check if it is an objectgo deeper in the tree! could you please help me in this regard
var new_json = config;
async.each(Object.keys(config), function(key) {
if (key == "test") {
delete new_json[key];
}
while (typeof (new_json[key]) == "object") {
// How can I handle it here
}
});
console.log("done!");
This function should do it:
function clean(obj,target) {
var tmpobj = obj;
for (var key in tmpobj) {
if (key === target) {
delete obj[key];
}
else if (typeof obj[key] === "object") {
obj[key] = clean(obj[key],target);
}
}
return obj;
}
called this way:
json_struct = clean(json_struct,"test")
Below Recursion code will work. But you need to list of acceptable fields or not acceptable fields and based on that you need to change the below condition IF you know not acceptable fields then use below conditions.
unAcceptableFields.indexOf(key) > 0
var acceptableFields = ["name","version","storage","db", "test9", "test10","tets2", "test8", "test9", "test10" ];
console.log(removeUnwantedFields(testObject, acceptableFields));
function removeUnwantedFields(jsData,acceptableFields) {
var key;
if (jsData) {
for (key in jsData) {
if (acceptableFields.indexOf(key) == -1) {
delete jsData[key];
}
else if(typeof jsData[key] === "object"){
jsData[key] = removeUnwantedFields(jsData[key],acceptableFields);
}
}
}
return jsData;
}
Refer this URL http://jsfiddle.net/55x2V/

Categories