In my web application, Web API returns following JOSN object.
[
{
"templateID":1,
"template":"{\r\n \"Body\": \"sample date hete hee. Name\"\r\n}"
},
{
"templateID":2,
"template":"{ \"Body\": \"you soon.\" }"
}
]
I need to get Body value from each JSON node by passing templateID. The problem is you can see this JSON has \r\n in some places.How ever I need get the Body value of each node. As an example if I pass 1 I need to get sample date hete hee. Name if pass 2 i need you soon. how can I do it?
I tried this. but its not working
var data2 = [
{
"templateID":1,
"template":"{\r\n \"Body\": \"sample date hete hee. Name\"\r\n}"
},
{
"templateID":2,
"template":"{ \"Body\": \"you soon.\" }"
}
]
function usersBasedOnIDs(isShow,field){
var filtered=data2.filter(function(item){
return item[field] == isShow;
});
console.log(filtered);
}
usersBasedOnIDs(1,'templateID');
item[field] == isShow;
You don't have any object where this condition will be true, i guess you want to filter element based on ID and then see it's body value
var data2 = [{
"templateID": 1,
"template": "{\r\n \"Body\": \"sample date hete hee. Name\"\r\n}"
},
{
"templateID": 2,
"template": "{ \"Body\": \"you soon.\" }"
}
]
function usersBasedOnIDs(isShow, field) {
var filtered = data2.filter(function(item) {
return item[field] == isShow;
});
console.log(filtered && JSON.parse(filtered[0].template).Body);
}
usersBasedOnIDs(1, 'templateID');
Simply try this
var x = [
{
"templateID":1,
"template":"{\r\n \"Body\": \"sample date hete hee. Name\"\r\n}"
},
{
"templateID":2,
"template":"{ \"Body\": \"you soon.\" }"
}
]
for(let i=0;i<x.length;i++){
let y = x[i].template;
console.log(JSON.parse(y).Body);
}
function usersBasedOnIDs(templateId) {
let result = data2.find(function(item) {
return item.templateId === templateId;
});
if(result === undefined) {
return;
} else {
return JSON.parse(result.template).Body;
}
}
console.log(usersBasedOnIDs(1));
Related
I need to remove an entry from an array by searching for the id value.
The data looks like this:
data = [ { "id": "02" }, { "id": "03" } ];
And I need a method like:
remove(keyValue) {
// do something here
}
Usage example:
remove('02');
Then it would search the id key with value "02" and remove the data so it would remove like this:
data = [ { "id": "03" } ];
How can I do this?
Works if key is "id", and if you are sure there won't be repeated values:
var data = [ { "id": "02" }, { "id": "03" } ];
function removeVal(value) {
var removeIndex = -1;
data.forEach((obj, index) => {
if (obj.id === value) {
removeIndex = index;
}
});
data.splice(removeIndex, 1);
console.log(data);
}
removeVal("02");
You could implement something like this https://stackblitz.com/edit/typescript-g3gty2
where the method remove accepts the initial array, the key and the value to remove.
function remove(data: any[], key: string, value: any) {
return data.filter(d => d[key] !== value);
}
If you use Typescript remove quotes from property names.
data = [ { id: "02" }, { id: "03" } ];
You can use findIndex function to get the index of specific element. After you got the index you can delete the element with splice function.
remove(keyValue: String) {
let objectIndex = this.data.findIndex(e => e.id == keyValue);
if(objectIndex != -1) {
this.data.splice(objectIndex, 1); // Remove one element from array
}
}
I am struggling with filtering an array of partners. Just for the sake of simplicity, I am defining partner object as below:
var partners = [
{ partnerCategory: "Gold", programs: ["Enterprise"] },
{ partnerCategory: "Silver", programs: ["Core", "Enterprise"] },
{ partnerCategory: "Silver", programs: ["Enterprise"] }
];
Now there are 2 picklists: partnerCategory and programs. If the user selects any value from the picklist, then I am populating an object filterCriteria.
Now I am defining filterCriteria in various ways to get an idea of the records that should be returned.
OPTION 1
var filterCriteria = [
{ fieldName: "partnerCategory", fieldValue: ["Silver"] }
];
2nd and 3rd record should be returned.
OPTION 2
var filterCriteria = [
{ fieldName: "partnerCategory", fieldValue: ["Silver", "Gold"] }
];
No record should be returned
OPTION 3
var filterCriteria = [
{ fieldName: "partnerCategory", fieldValue: ["Silver"] },
{ fieldName: "programs", fieldValue: ["Enterprise"] }
];
2nd and 3rd records should be returned.
OPTION 4
var filterCriteria = [
{ fieldName: "partnerCategory", fieldValue: ["Silver"] },
{ fieldName: "programs", fieldValue: ["Enterprise", "Core"] }
];
Only 2nd record should be returned.
So basically if a value is present in filterCriteria object, then the record should have all the values present in the filter.
I am using the below code to get the output, but I am missing something:
var result = partners.filter(function (obj) {
return filterCriteria.every(function (c) {
var value = obj[c.fieldName];
if (typeof value === 'object') {
return Object.keys(value).every(function (key) {
return c.fieldValue.indexOf(value[key]) > -1
})
}
else
return c.fieldValue.indexOf(value) > -1
})
});
EDIT: Now I am using this code, but option 2 and 4 are not giving the desired output:
var result = partners.filter(function (partner) {
return filterCriteria.every(function (c) {
var value = partner[c.fieldName];
console.log(value);
if (typeof value === 'object') {
return c.fieldValue.length==value.length &&
c.fieldValue.every(function(v,i){return v==value[i];});
}
else
return c.fieldValue.indexOf(value) > -1;
})
})
Is it possible to determine if a JSON object contains a specified "fieldname".
For example:
If I have a JSON Object such as:
{"event":
[
{"query":
{"id":
[
{"timestamp_usec":"1316596939223064"}
],
"query_text":"sometext"
}
},
{"query":
{"id":
[
{"timestamp_usec":"1316318681908642","type":"sometype","abc":"someabc"},
{"timestamp_usec":"1316318679366796"}
],
"query_text":"someothertext"
}
},
//...More...//
]
}
What can I use as my conditional within an if statement to determine if a particular "id object" contains an "abc"?
More Simply:
FOR ALL jsonpath id's
IF jsonpath.id **CONTAINS** "abc"
THEN do something
ELSE do something different
END LOOP
I'm looking for the jQuery function to achieve this (if there is one!).
My Code:
$.getJSON("test.json", function(data) {
var search = data.event
$.each(data.event, function(i, item) {
var searchMeta = data.event[i].query.id;
$.each(searchMeta[i], function(i, deeper){
if (searchMeta[i]. == "abc"){
//do something
} else {
//do something different
}
})
})
});
I know in the above example I could essentially achieve what I want by looping on the number of id objects, eg If num < 1. But I am not sure how uniform my data is throughout more than one .json file.
Try defining a function to call for each Object within data object
// property `name` to check
var name = "abc";
var check = function check(obj, name) {
// if `obj` is `Object` ,
// and `obj` has property `name` ,
// do stuff
if (/Object/.test(obj.constructor.toString())
&& obj.hasOwnProperty(name)) {
console.log(name + " found")
}
// else , do other stuff
else {
console.log(name + " not found")
}
};
$.each(data.event, function(key, value) {
check(value, name);
$.each(value.query, function(k, v) {
check(v, name);
// if `v` is an `Object` , call check for
// call `check` on each `v` `Object`
if (typeof v === "object") {
$.each(v, function(_k, _v) {
check(_v, name);
})
};
});
});
var data = {
"event": [{
"query": {
"id": [{
"timestamp_usec": "1316596939223064"
}],
"query_text": "sometext"
}
}, {
"query": {
"id": [{
"timestamp_usec": "1316318681908642",
"type": "sometype",
"abc": "someabc"
}, {
"timestamp_usec": "1316318679366796"
}],
"query_text": "someothertext"
}
}
//...More...//
]
};
var data = {
"event": [{
"query": {
"id": [{
"timestamp_usec": "1316596939223064"
}],
"query_text": "sometext"
}
}, {
"query": {
"id": [{
"timestamp_usec": "1316318681908642",
"type": "sometype",
"abc": "someabc"
}, {
"timestamp_usec": "1316318679366796"
}],
"query_text": "someothertext"
}
}
//...More...//
]
};
// property `name` to check
var name = "abc";
var check = function check(obj, name) {
// if `obj` is `Object` ,
// and `obj` has property `name` ,
// do stuff
if (/Object/.test(obj.constructor.toString())
&& obj.hasOwnProperty(name)) {
var res = {};
res[name] = obj[name];
$("body").append(JSON.stringify(res) + " found")
}
// else , do other stuff
else {
console.log(name + " not found")
}
};
$.each(data.event, function(key, value) {
check(value, name);
$.each(value.query, function(k, v) {
check(v, name);
// if `v` is an `Object` , call check for
// call `check` on each `v` `Object`
if (typeof v === "object") {
$.each(v, function(_k, _v) {
check(_v, name);
})
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
jsfiddle http://jsfiddle.net/yenp6t8v/
JSON.stringify(json) this will give you json as string then you can do REGEX to check if there is file in the json.
I am trying to convert a JSON string in a Javascript object literal. I think it is possible with some loops, but i couldn't get it done. The target structure is shown below, "chartData".
Fiddle can be found here: http://jsbin.com/ajemih/13/edit
Here's the JSON data:
{
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
}
This should it look like after the conversion:
chartData = [[['loadMovement', 111],
['allMovement', 120],
['allLoad', 130]],
[['Load+Move', 671],
['allMovement', 280],
['allLoad', 910]]];
I think this would work:
Working demo: http://jsfiddle.net/jfriend00/YmjDR/
var data = {
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
};
var chartData = [];
for (var i in data) {
var item = data[i];
var outer = [];
// skip over items in the outer object that aren't nested objects themselves
if (typeof item === "object") {
for (var j in item) {
var temp = [];
temp.push(j);
temp.push(item[j]);
outer.push(temp);
}
}
if (outer.length) {
chartData.push(outer);
}
}
You could do something like this:
var chartData = []
for(var key in data) {
var properties = data[key];
if(typeof properties === "object") {
var array = [];
for(var propKey in properties) {
array.push([propKey, properties[propKey]])
}
chartData.push(array);
}
}
Check out the fiddle.
You need to map the data manually. Thats actually more a diligent but routine piece of work.
var jsonData = 'your json string';
Object.keys( jsonData ).map(function( key ) {
if( typeof jsonData[ key ] === 'object' ) {
return Object.keys( jsonData[ key ] ).sort(function( a, b ) {
return +jsonData[ key ][ a ] - +jsonData[ key ][ b ];
}).map(function( name ) {
return [ name, jsonData[ key ][ name ] ];
});
}
}).filter( Boolean );
The above code will sort each group by its numeric value and then map a new array in the required style. Since .map() possibly returns undefined values on non-object elements, we need to filter those out before or afterwards.
See http://jsfiddle.net/WjZB2/2/
I had similar problem.
My goal was to convert a list of strings into a valid format for http://ivantage.github.io/angular-ivh-treeview/
This was my starting point:
[
"A\\A1\\Test1",
"A\\A1\\Test2",
"A\\A2\\Test3",
"B\\Test4",
"B\\Test5",
"B\\B1\\Test6",
"B\\B1\\Test7",
"B\\B1\\Test8",
"C\\C1\\C1a\\Test9",
"C\\C1\\C1b\\Test10",
"C\\C2\\C2a\\Test11",
"C\\C2\\C2a\\Test12",
"C\\C2\\C2a\\Test13",
"C\\C3\\Test14",
"C\\Test15",
"C\\Test16"
]
And I needed following format:
[
{
"label": "Selected Tests",
"children": [
{
"label": "A",
"children": [
{
"label": "A1",
"children": [
{
"label": "Test1",
"value": true
},
{
"label": "Test2",
"value": true
}
]
},
{
"label": "A2",
"children": [
{
"label": "Test3",
"value": true
}
]
}
]
}
]
}
]
See my solution https://jsfiddle.net/ydt3gewn/
I have several objects like this:
I want to move type and value one step up so they will be next to field, and then delete data.
It looks like this when departments is converted to JSON:
[
{"field" : "DEPARTMAN_NO",
"data" : { "type":"numeric" , "comparison":"eq" , "value":11 }
},
{"field" : "DEPARTMAN_ADI",
"data" : { "type":"string" , "value":"bir" }
}
]
I have tried:
departments = grid.filters.getFilterData();
i = {};
for(var i in department) {
department = i.data;
delete.department.data;
};
but it dosen't work.
1) First, loop departments, each item we call it department;
2) You want to move department.data's properties to department, From another angle, you can move department's properties to department.data and return department.data, code like:
var departments = [{
"field": "DEPARTMAN_NO",
"data": {
"type": "numeric",
"comparison": "eq",
"value": 11
}
}, {
"field": "DEPARTMAN_ADI",
"data": {
"type": "string",
"value": "bir"
}
}],
department;
for (var i = 0, len = departments.length; i < len; i++) {
department = departments[i]; // department
for (var key in department) {
if (key !== 'data' && department.data) {
department.data[key] = department[key];
}
}
departments[i] = department.data || department; // if no department.data, no change
}
console.log(departments);
result:
view the full demo http://jsfiddle.net/KVYE5/
I wrote a little npm package that does what you're asking for: moving a property up a level in an object.
You can get it here: https://www.npmjs.com/package/move-property-up-a-level
Usage
var movePropertyUpALevel = require('movePropertyUpALevel');
var fakeObj = {
poodle: {
first: {
hey: 'you'
},
second: 'meAgain'
}
};
movePropertyUpALevel(fakeObj, 'poodle');
console.log(fakeObj.first.hey);
//'you'
console.log(fakeObj.poodle);
//undefined
obj =
[
{"field" : "DEPARTMAN_NO",
"data" : { "type":"numeric" , "comparison":"eq" , "value":11 }
},
{"field" : "DEPARTMAN_ADI",
"data" : { "type":"string" , "value":"bir" }
}
];
for ( var item in obj ) {
if ( obj[item].field && obj[item].data ) { //check the 'field' and 'data' exist
obj[item].field = {
dept : obj[item].field , //department name is put into a property
type : obj[item].data.type, //so is data.type and data.value..
value: obj[item].data.value //..all are now contained in 'field'
};
delete obj[item].data; //remove the 'data' object
}
}
console.log(obj);
department.type = department.data.type;
department.value = department.data.value;
delete department['data'];