I have two json object with similar key question.
var data = {"question":[{
QuestionID : counter1,
QuestionText: question1,
Choices:[{ChoiceID:100,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:101,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}]};
var data1 = {"question":[{
QuestionID : counter2,
QuestionText: question2,
Choices:[{ChoiceID:103,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:105,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}]};
I want to concate them into one json object with key 'question' and value will be array like below
var final = {"question":[
{
QuestionID : counter1,
QuestionText: question1,
Choices:[{ChoiceID:100,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:101,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
},
{
QuestionID : counter2,
QuestionText: question2,
Choices:[{ChoiceID:103,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:105,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}
]};
I tried many ways and below way close to my destination but it creats array of data and data1 object
var jsons = new Array();
jsons.push(data);
jsons.push(data1);
My problem will solve if i can concate question:Object and question:Array[2] where each index contains object. Final output will be question:Array[3]
Any help will be highly appreciated.
Thanks in advance.
I solved this problem by
var index = 0; // number of question
$.each(previousData.question,function(){
finalArray[index] = previousData.question[index]; //contain array
index++; //here index is number of question
});
finalArray[index] = data.question;
data = {'question': finalArray }; // convert array to object
You can merge through jquery
var final = $.merge(data, data1);
Well, your code is actually pushing two objects into a list so u get a list of objects. In your case, the first element is data and the second is data1. So you wouldnt actually get the required result.
Since you want an object try this
/* assuming data and data1 are created and both have the key question */
var final = {'question': [data.question, data1.question] };
// or using the concat feature
var final = data.question.concat(data1.question);
Related
I try to prepare data for JSON encode:
var i = 0
for (data) in students {
var variableNewData = ["\(students[i].id)":["timestampValue":"\(students[i].timestampValue)"]]
variableNewData["updateTime"] = ["updateTime":"\(students[i].timestampValue)"]
variableNewData["createTime"] = ["createTime":"\(students[i].timestampValue)"]
i += 1
let finalParameter = ["class":variableNewData]
print("LastParameter:",finalParameter)}
}
I need data in this format:
{"class": {"studentOne": {"timestampValue": "2020-02-04" },"studentTwo ":{ "timestampValue": "2020-02-05" }},"createTime": "2020-03-30","updateTime": "2020-03-30"}
but I get this: class, id, timestampValue seems ok, but create and update time are wrong.
thanks for any suggestions.
{"class":{"createTime":{"createTime":"2020-03-30"},"studentOne":{"timestampValue":"2020-02-04"},"updateTime":{"createTime":"2020-03-30"}}}
Let’s look at your desired format in a “pretty” format:
{
"class": {
"studentOne": {
"timestampValue": "2020-02-04"
},
"studentTwo ": {
"timestampValue": "2020-02-05"
}
},
"createTime": "2020-03-30",
"updateTime": "2020-03-30"
}
So, for the key class, you have a value that is a subdictionary keyed by the student id, that itself contains yet another a dictionary with a single timestamp. So, I’d build this dictionary associated with class first:
var studentsDictionary: [String: [String: String]] = [:]
for student in students {
studentsDictionary[student.id] = ["timestampValue": student.timestampValue]
}
You then have createTime and updateTime that are at the top level, alongside class (presumably the data of creation and update of the whole class, not the individual students). Anyway you could build the top level dictionary, like so:
let dictionary: [String: Any] = [
"class": studentsDictionary,
"updateTime": "2020-02-05",
"createTime": "2020-02-05"
]
Obviously, you’d want to set updateTime and createTime for timestamp values for the class, but hopefully that illustrates the idea.
And we could then build the JSON representation of all of this with:
let data = try! JSONSerialization.data(withJSONObject: dictionary) // add `option: .prettyPrinted` if you want to see pretty version
//
// if you want to check the above `data`:
//
// let string = String(data: data, encoding: .utf8)!
// print(string)
//
Note, that the updateTime and createTime are not at the student level, so I’m not sure where you wanted to get those values from.
By the way, if you’re interested, a more concise way to build that studentDictionary dictionary is with the Dictionary(uniqueKeysWithValues:):
let studentsDictionary = Dictionary(uniqueKeysWithValues: students.map { student in
(student.id, ["timestampValue": student.timestampValue])
})
Try setting the updateTime and createTime key values as simple strings instead of dictionaries of their own.
variableNewData["updateTime"] = "\(students[i].timestampValue)"
variableNewData["createTime"] = "\(students[i].timestampValue)"
I have a tableView with different kinds of infos, each coming from a different array.
I could not work with dictionaries because then the list would have been unordered and I could not work with classes, because I have different lists with all kinds of dynamic entries (properties are always different etc.)
Here my problem:
I want to implement a search function. But when I use the filter function for one array, it changes of course based on the implemented condition but the other 5 stay the same => I can't reload the tableView because the array information does not match anymore ...
Here the arrays:
var categoryItemUIDs = [String]()
var categoryItemDescriptions = [String]()
var categoryItemLfdNrs = [Int]()
var categoryGivenOuts = [Bool]()
var categoryGivenTos = [String]()
var categoryGivenAts = [String]()
var categoryStorageLocations = [String]()
In the tableView(cellForRowAtIndexPath method):
cell.customTextLabel?.text = categoryItemLfdNrs[indexPath.row]
cell.customDetailTextLabel.text = categoryItemDescriptions[indexPath.row]
Here the searchBar(textDidChange) method:
self.categoryItemDescriptions.filter { $0.lowercased().contains(searchText.lowercased()) }
Now I get an array back with reduced size, but all the other arrays stay the same... Is there maybe another way to avoid this problem? I already tried type aliases but it did not work out.
I would appreciate any help!
Kind regards,
When it goes to such a big count of arrays, the time for your specific type comes.
The simple solution is to create something like
struct Category {
var uid: String
var description: String
// ...
var storageLocation: String
}
The you have simply something like
var items: [Category]
And you can still do simple things in cellForRowAtIndexPath
cell.customTextLabel?.text = items[indexPath.row].lfdnrs
cell.customDetailTextLabel.text = items[indexPath.row].description
And only 1 array to filter
items.filter { $0.description.lowercased().contains(searchText.lowercased()) }
So overall advice is to solve different problem (here I suggested the solution of the having your data in the app problem instead of filtering multiple arrays with one condition)
try
var categoryItemUIDs = ["aaa","bbb","ccc"]
var categoryItemDescriptions = ["ddd","eee","fff"]
var categoryItemLfdNrs = [0,1,2]
struct data {
var id = ""
var desc = ""
var item = 0
init(id :String, desc:String, item:Int)
{
self.id = id
self.desc = desc
self.item = item
}
}
//var cat = [data]()
//for i in 0..<categoryItemUIDs.count {
// cat.append(data(id:categoryItemUIDs[i], desc:categoryItemDescriptions[i],item:categoryItemLfdNrs[i] ))
//}
//more swift
let cat = (0..<categoryItemUIDs.count).map { (i) -> data in
return data(id:categoryItemUIDs[i], desc:categoryItemDescriptions[i],item:categoryItemLfdNrs[i] )
}
print (cat)
let catFilter = cat.filter { $0.id == "aaa" }
print (catFilter)
I need to get the inner object value in localStorage.i.e object inside the object.
var filter = {
filterWord: null,
userId: null
}
filter.filterWord = listCAO.sortName;
filter.userId = listCAO.currentUser;
listCAO.filterBreadcumText.push(filter);
localStorage.setItem('entityBreadCumText', listCAO.filterBreadcumText);
LocalStorage only holds String pairs: 'string1'='string2'
So when you do localStorage.getItem('string1') it returns 'string2'.
If you want to store a Javascript Object, you need to convert it into a string first. JSON works best for that.
var myObj = [{'name': 'Paul', 'age': 22}, {'name': 'Steve', 'age': 68}];
myStr = JSON.stringify(myObj);
localStorage.setItem('myData', myStr);
Same when you read the data from localStorage
var myStr = localStorage.getItem('myData');
var myObj = JSON.parse(myStr);
var myName = myObj[0].name;
Or in one step
var myName = JSON.parse(localStorage.getItem('myData'))[0].name;
This may be another solution.
You can use it this way.
let obj = JSON.parse(localStorage.getItem('your_settings_name'));
let lobj: YourObject = <YourObject>obj;
If the data is stored as nested objects instead of an array as c14l 's answer, the syntax changes a little bit.
Let's store nested object first:
var myNestedObject = {"token": "Bearer", "profile": {"name":"Mustafa","expires_at":1678013824}};
myNestedStr = JSON.stringify(myNestedObject);
localStorage.setItem('myNestedData', myNestedStr);
Now let's see how to get the "name" from the nested object:
var nestedStr = localStorage.getItem('myNestedData');
var nestedObj = JSON.parse(nestedStr);
var nestedProfile = nestedObj.profile;
var nestedName = nestedProfile.name;
Or we can get "name" with a single line also:
var nestedNameWithOneLine = JSON.parse(localStorage.getItem('myNestedData')).profile.name;
I have a array, which has the bunch of object, i would like to filter the object by 'name' value, again i would like to omit those object from another array of object using underscore.
I know that we can do using earch, but i am not getting the proper approach to do this both..
any one help me to do this?
example :
incoming array:
var incomingArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
];
filter keys:
var omit = ['orange' ,'dog'];
//i need to check whether 'orange' or 'dog' are exist, if so..
var filtered = _.filter(incomingArray, function(obj, i){
return obj.name === omit[i]['name'];//this is wrong i need to loop again how?
});
var anotherArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
]
return only the array without the omit like this:
var outgoingArray = [
{"name":"apple"},
{"name":"cat"},
{"name":"egle"} ]
how we could achieve this with proper approach?
demo
You were nearly there! Use indexOf to check that the name does not belong in the omit array:
var filtered = _.filter(incomingArray, function(obj) {
return omit.indexOf(obj.name) == -1;
});
i am using the extjs. i need to retrieve distinct data from store as per requirement. In my store contains single list not nested list in that have regions like AMERICAS , North Sea and SE Asia. these region it self have subRegion,vesselName and vesselType values. I need to retrive unique value based on region, bacasue it contains many duplicate records. I have tried like as below, but it is not working me. Can anybody tel me how to achieve ?. great appreciated. Thank you.
var vesselStore=Ext.getStore('VesselStatusReportStore');
var arr=new Array();
var obj;
vesselStore.each(function(rec,index)
{
obj=new Object();
if(rec.get('region')=='AMERICAS'){
obj.subRegionAmerica=rec.get('subRegion');
obj.vesselNameAmerica=rec.get('vesselName');
obj.vesselTypeAmerica=rec.get('vesselType');
}
if(rec.get('region')=='NorthSea'){
obj.subRegionNorthSea=rec.get('subRegion');
obj.vesselNameNorthSea=rec.get('vesselName');
obj.vesselTypeNorthSea=rec.get('vesselType');
}
if(rec.get('region')=='SE Asia'){
obj.subRegionSEAsia=rec.get('subRegion');
obj.vesselNameSEAsia=rec.get('vesselName');
obj.vesselTypeSEAsia=rec.get('vesselType');
}
arr.push(obj);
console.log(obj);
});
Json:
[ {
"region" : "AMERICAS",
"startDate" : null,
"subRegion" : "US",
"vesselName" : "Thoma-Sea � Hull #147",
"vesselType" : "PSV"
},
{
"region" : "AMERICAS",
"startDate" : null,
"subRegion" : "US",
"vesselName" : "Thoma-Sea � Hull #148",
"vesselType" : "PSV"
},
{
"region" : "AMERICAS",
"startDate" : null,
"subRegion" : "Mexico",
"vesselName" : "Thoma-Sea � Hull #148",
"vesselType" : "PSV"
}]
It looks like you want to use collect. http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Store-method-collect
vesselStore.collect('region')
This section doesn't make sense:
obj=new Object();
if(rec.get('region')=='AMERICAS'){
obj.subRegionAmerica=rec.get('subRegion');
obj.vesselNameAmerica=rec.get('vesselName');
obj.vesselTypeAmerica=rec.get('vesselType');
}
if(rec.get('region')=='NorthSea'){
obj.subRegionNorthSea=rec.get('subRegion');
obj.vesselNameNorthSea=rec.get('vesselName');
obj.vesselTypeNorthSea=rec.get('vesselType');
}
if(rec.get('region')=='SE Asia'){
obj.subRegionSEAsia=rec.get('subRegion');
obj.vesselNameSEAsia=rec.get('vesselName');
obj.vesselTypeSEAsia=rec.get('vesselType');
}
arr.push(obj);
You are basically saying "Whatever the region is, copy the record to obj, then add that obj to my array".
I believe you meant something more along these lines:
var vesselStore=Ext.getStore('VesselStatusReportStore');
var iRegions = [];
vesselStore.each(function(rec,index)
{
var iRegionName = rec.get('region');
// Make sure theres a array item with the region name,
// if not create a blank array;
iRegions[ iRegionName ] = iRegions[ iRegionName ] || [];
// Add the record to its corresponding array item.
// (If you don't want the full record, you can just get the
// fields individually like you did in your code).
iRegions[ iRegionName ] = rec;
}
console.log( iRegions );