How to get expected json value in jQuery? - javascript

I am making a json after watching a json object ,But I am getting more key or text .I need to remove that text.
I am getting this output
function mapItem(inputItem) {
var item = {};
item[inputItem.id] = JSON.parse(sessionStorage.getItem(inputItem.id));
for (k in inputItem.children) {
if (/^not-/.test(inputItem.children[k].id)) {
item[inputItem.id].commandList.push(mapItem(inputItem.children[k]));
}else{
item[inputItem.id].testCaseList.push(mapItem(inputItem.children[k]));
}
}
return item;
}
http://jsfiddle.net/tJ7Kq/7/
I THINK PROBLEM ON THIS LINE
item[inputItem.id].commandList.push(mapItem(inputItem.children[k]));

Try this.
http://jsfiddle.net/tJ7Kq/8/
function mapItem(inputItem) {
//var item = {};
var item = JSON.parse(sessionStorage.getItem(inputItem.id));
for (k in inputItem.children) {
if (/^not-/.test(inputItem.children[k].id)) {
item.commandList.push(mapItem(inputItem.children[k]));
}else{
item.testCaseList.push(mapItem(inputItem.children[k]));
}
}
return item;
}

Related

Check if an Object contains any value for the Same key in a Different Object JS

Sorry for the Lost Post . The problem statement
I have this URL -
http://www.XXXXX.com/mobiles-tablets/mobiles/apple?q=&idx=letsTango_default_products&p=0&hFR%5Bcategories.level0%5D%5B0%5D=Mobiles%20%26%20Tablets%20%2F%2F%2F%20Mobiles%20%2F%2F%2F%20Apple&nR%5Bprice.AED.default%5D%5B%3C%3D%5D%5B0%5D=2560&is_v=1
I had to extract all the query-params in a object like a key value pair .
and then check from a different object if any of these query-params with same key has any matching value .
This is my solution , I am new to java script and so i want to confirm if this is the right way to go about.
The solution so far works for all the cases . just let me know if the performance can be enhanced or any better way.
Fiddle Link for the Solution - http://jsfiddle.net/rahulsingh09/tqpzv/6/
code
var callingUrl = "http://www.letstango.com/mobiles-tablets/mobiles/apple?q=&idx=letsTango_default_products&fsrc=sort_price,brand&p=0&hFR%5Bcategories.level0%5D%5B0%5D=Mobiles%20%26%20Tablets%20%2F%2F%2F%20Mobiles%20%2F%2F%2F%20LG&nR%5Bprice.AED.default%5D%5B%3C%3D%5D%5B0%5D=2560&nR%5Bprice.AED.default%5D%5B%3E%3D%5D%5B0%5D=1138&is_v=1";
if (callingUrl) {
var queryParam = {};
var split = callingUrl.split("?");
if (split.length > 1) {
var query = split[1].split("&");
if (query.length > 1) {
_.each(query, function(q) {
var key = decodeURIComponent(q.split("=")[0]);
var value = decodeURIComponent(q.split("=")[1]);
if (value.indexOf(",") !== -1) {
value = value.split(",");
}
queryParam[key] = value;
})
}
}
}
if (!_.isEmpty(queryParam)) {
var value = {
"fsrc": ["brand"]
};
for (var key in value) {
if (value.hasOwnProperty(key)) {
for (var k in queryParam) {
if (queryParam.hasOwnProperty(k)) {
if (k === key) {
var index = _.intersection(value[key], queryParam[k]);
if (index.length > 0) {
console.log("Matches");
} else {
console.log("fails");
}
}
}
}
}
}
please note - the url can change depending upon the browser url.
Thanks in advance , I want to get the best performance possible for this problem.

Search word from json file in node js

i had json file in that data is like this
[{"wingnum":0,"name":"vatsal chauhan","email":"chauhanvatsal81#yahoo.com","city":"bhavnagar","address":"asdf"},
{"wingnum":0,"name":"hardik","email":"hardikdave#gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"},
{"wingnum":0,"name":"kevin","email":"kevin#gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"},
{"wingnum":0,"name":"rohit","email":"rohit#gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"}]
I want to search only name using fs.readfile or by any other option my code is shown below
exports.getdata = function(req,res,next){
console.log('reqobj',req.body.params.name);
fs.readFile('./server/api/Appartment/appartment.json', 'utf8',function read(err, data) {
/*obj = JSON.parse(data);
console.log(obj);*/
if (err) {
throw err;
}
else{
if (data === ""){
console.log('data does not exsist');
}
else{
console.log('exsist data getdata');
var arrayobject = JSON.parse(data);
console.log(arrayobject);
return res.status(200).json(data);
}
}
// res.end();
});
};
this code gives all data but i want to just get name according to parameter passed
like autocomplete
Once you've parsed the JSON and have the object in a variable, pass the object and the name to be searched in this function :
var searchname=function(x, somename){
for(var i = 0; i < x.length; i++) {
if (x[i]['name']==somename){
return i;
}
}
return -1; //This means no match found
}
For example, you can get the document containing the name you want by doing this in your code :
var index=searchname(arrayobject, req.body.params.name);
if (index!=-1){
console.log(json[index]);
// Or do something else with json[index]
}
Update: If you want to do a search within the object itself, and get all the names matching a criteria, here's how the function would change :
var searchname=function(x, somename){
var result=[];
for(var i = 0; i < x.length; i++) {
if (x[i]['name'].indexOf(somename)>-1){
result.push(x[i]['name']);
}
}
return result; //Array containing matched names. Returns empty array if no matches found.
}
console.log(searchname(arrayobject, req.body.params.name)); //To display the working of above for testing.

Remove Local Storage JSON Object & Rebuild Array

I'm struggling with the task of removing an item from the LocalStorage...here is my LocalStorage data JSON.
{
"1461569942024" :
{"t_id":1461569942024,"t_build_val":"PreBuild1","t_project_val":"18"},
"1461570048166" :
{"t_id":1461570048166,"t_build_val":"PreBuild2","t_project_val":"17"}
}
here is what I was trying to do:
function removeItem(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
var newData = removeItem(localStorage['data'], '1461569942024');
I would like to remove na object based on object key eg:1461570048166 and re-save whole array again to the LocalStorage.
Thanks
Try this code
var json = {
"1461569942024": {
"t_id": 1461569942024,
"t_build_val": "PreBuild1",
"t_project_val": "18"
},
"1461570048166": {
"t_id": 1461570048166,
"t_build_val": "PreBuild2",
"t_project_val": "17"
}
};
function deleteItem(input, key) {
delete input[key];
return input
}
localStorage.setItem("localStore", JSON.stringify(json));
localStorage.setItem("localStore", JSON.stringify(deleteItem(JSON.parse(localStorage.getItem("localStore")), '1461570048166')));
JSON.parse(localStorage.getItem("localStore"));

Filtering with AngularJS within an Object

I've been beating myself up over this for the past two days and I cant find a solution. I'm trying to filter a set of articles based off of their tags. I've used an ng-repeat to repeat the article and display the data coming from my API. But cant seem to get the filter correct.
Here is an example of the Article Object
{"id":"05390344-57f8-4f2a-ada0-0705edacd0ef","type":"Article","title":"Lorem title","topics":[{"Id":"bb2a6222-34b1-4abd-8d19-c07eb7ff4d0c","Name":"Pajamas"},{"Id":"7f752e06-092b-473a-9f4e-b79796c7ab7b","Name":"Undies"},{"Id":"bd533c42-90e9-4dce-9316-e3be6c8fc55c","Name":"Briefs"}],"synopsis":"<p>Lorem Ipsem synposis</p>","date":"August 20, 2014","time":"9:28 AM","source":"Localhost","url":"#"}
My controller contains
$scope.filterTopics = {};
function getChecked(obj) {
var checked = [];
for (var key in obj) if (obj[key]) checked.push(key);
return checked;
}
$scope.searchFilter = function (row) {
var topicChecked = getChecked($scope.filterTopics);
if (topicChecked.length == 0)
return true;
else {
if ($scope.filterTopics[row.topics])
return true;
}
};
$scope.$watch('cards', function (cards) {
$scope.count = 0;
angular.forEach(cards, function (card) {
if (card.filterTopics) {
$scope.count += 1;
}
})
});
My view to create the ng-repeat
<div ng-repeat="article in articles | filter: searchFilter">
Then I have checkboxes that I can click to pass search filter the topic Id
ng-model="filterTopics['#topic.Id']
Any help would be great!!!!
Solution was to add a for loop to grab each object
for (var i in row.topics) {
if (topicChecked.indexOf(row.topics[i].Id) != -1) {
return true;
}
}

How to get a SharePoint-UserField with JavaScript?

Hallo,
i need to write some javascript that gets the contents of a userfield in a sharepoint-website. I can get most fields with the javascript-function 'getTagFromIdentifierAndTitle' of Using Javascript to Manipulate a List Form Field, but not UserFields.
So how can i get UserFields?
Thanks!
I traced how address book interacts with user field. To get values it uses function getUplevel(ctx) and to set values can be used function EntityEditorCallback(xml, ctx). First function will return html/xml mixed string with user information. Second function input must be special formatted xml string.
// Get values
var ctx='ctl00_m_g_e5a1501a_..._ctl04_ctl00_ctl00_UserField';
var values=getUplevel(ctx);
alert(values);
// Set values
var xml='<Entities Append="False" Error="" Separator=";" MaxHeight="3">'+
'<Entity Key="DOMAIN\\loginname" DisplayText="Display Name" IsResolved="True" Description="DOMAIN\\loginname">'+
'<ExtraData>'+
'<ArrayOfDictionaryEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
'<DictionaryEntry><Key xsi:type="xsd:string">DisplayName</Key><Value xsi:type="xsd:string">Display Name</Value></DictionaryEntry>'+
'<DictionaryEntry><Key xsi:type="xsd:string">Email</Key><Value xsi:type="xsd:string">Display.Name#domain.ee</Value></DictionaryEntry>'+
'<DictionaryEntry><Key xsi:type="xsd:string">SPUserID</Key><Value xsi:type="xsd:string">1</Value></DictionaryEntry>'+
'<DictionaryEntry><Key xsi:type="xsd:string">PrincipalType</Key><Value xsi:type="xsd:string">User</Value></DictionaryEntry>'+
'</ArrayOfDictionaryEntry>'+
'</ExtraData>'+
'<MultipleMatches />'+
'</Entity>'+
'</Entities>';
EntityEditorCallback(xml,ctx);
Tricky part is ctx attribute that must be target field id. In user field html there is no title attribute, so to find right element by display name with js is very complex. I suggest to pass field id to the javascript from server side. For example you can create custom WebPart where you write to the page field id-s from collection SPContext.Current.FormContext.FieldControlCollection.
Here is the custom code that I put together. It relies on the exact HTML that SharePoint uses for the PeoplePicker. It does work on both IE and Firefox. For the columnName parameter, pass the "public" name of the column, not the internal name.
function getParentElementByTagName(baseNode, tagName)
{
var currNode;
if(baseNode !== null)
{
currNode = baseNode.parentNode;
while((currNode !== null) && (currNode.nodeName != tagName))
{
currNode = currNode.parentNode;
}
return currNode;
}
else
{
return null;
}
}
function getPeoplePickerCell(columnName)
{
var search = 'FieldName="' + columnName + '"';
var nodes = document.getElementsByTagName("TEXTAREA");
for(var i=0; i < nodes.length; i++)
{
if(nodes[i].title == "People Picker")
{
var outerCell = getParentElementByTagName(nodes[i], "SPAN").parentNode.parentNode;
if(outerCell.innerHTML.indexOf(search) > 0)
{
return nodes[i].parentNode;
}
}
}
return null;
}
function getSPPeoplePicker(columnName, value)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
return cell.childNodes[0].innerHTML;
}
else
{
return null;
}
}
function setSPPeoplePicker(columnName, value)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
cell.childNodes[0].innerHTML = value;
cell.childNodes[1].value = value;
}
}
function disableSPPeoplePicker(columnName)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
disableElement(cell.childNodes[0]);
disableElement(cell.childNodes[1]);
}
}
function enableSPPeoplePicker(columnName)
{
var cell = getPeoplePickerCell(columnName);
if(cell !== null)
{
enableElement(cell.childNodes[0]);
enableElement(cell.childNodes[1]);
}
}

Categories

Resources