How to parse through a JSON object Map - javascript

If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance

What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}

for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id

Related

How To Add A String Inside An Object For The Given Example

Hi iam finding the best way to add a string inside the given object.Any help would be appreciated
my String is 'created'
Down Below Is My Data
{
"id": "222",
"list": [
{
"name": "Tony",
}
],
iam trying to insert 'created' in the data like this
{
"id": "222",
"list": [
{
"name": "Tony",
"type":"created"
}
]
The string you've provided looks a lot like JSON data. You can convert a JSON string to an actual javascript object by using the JSON.parse(string) method.
With this object we then can query it's list property - which in your case is an array of objects - and add a new property type to each of the arrays elements. The final step is converting the object back to a JSON string using the JSON.stringify(object) method.
Here's an example:
let str = `{
"id": "222",
"list": [
{
"name": "Tony"
}
]
}`;
let data = JSON.parse(str);
data.list.forEach(element => {
element.type = "created";
});
str = JSON.stringify(data);
console.log(str);
const myObj = {
"id": "222",
"list": [
{
"name": "Tony",
}
],
};
myObj.list[0].type = "created";
This is the way you can do this. But you'd better use secified index of list items;
const index = 0; // Or any other way to get this
myObj.list[index].type = "created";

How to create a new json out of three jsons?

I have 3 different jsons, I need to extrapolate some data from each and create a new json with it. The three jsons have an id identifier in common, a unique identifier, so We could use that as a match since they are actually three different big jsons.
On json one we have "id":"265", on two and three "article_id":"265", so these can be the reference point when we loop.
I never worked with json this way so I wouldn't know how to approach it. I have put jQuery and JS as tags as they're what I know best.
1
{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
}
2
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
}
3
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}
So the end result I am looking for is a single json exactly like this, we take id and title as objects from json 1, then we grab original_name from json two and year object from json three and we'll have:
{
"id":"265",
"title":"Battle of Gettysburg",
"original_name":"United States",
"year":"1863"
}
NOTE
The json above are just examples, in reality they are three huge lists, what I could do (manually), is to join them in order to have a single json.
There is some terminology confusion here; based on your comments you could be asking one of two very different questions. Fortunately one of them is very simple to answer so let's do both.
(I am handwaving past the details of loading json strings into the browser and converting them into javascript objects.)
If you have three objects
...then this is just a matter of plucking out the fields you need individually when constructing an output object:
var in1 = {
"id": "265",
"title": "Battle of Gettysburg",
"page_id": "4849",
"language_id": "en",
"original_time": "July 1\u20133, 1863"
};
var in2 = {
"id": "185",
"original_name": "United States",
"country_id": "24",
"article_id": "265"
}
var in3 = {
"id": "73",
"month": "July",
"year": "1863",
"suffix": "",
"article_id": "265"
}
// construct a new object using the selected fields
// from each object in1, in2, or in3:
var out = {
id: in1.id,
title: in1.title,
original_name: in2.original_name,
year: in3.year
}
console.log(out);
If you have three lists of objects:
...in this case it's a lot more complicated (and a lot more interesting). In this case you would need to match fields from the objects in each list which share the same IDs.
The following is definitely not the most efficient or memory-conserving way to do this; I've spread things out to (hopefully) make it easier to follow what it's doing.
I'm making two assumptions:
within each list, all IDs are unique (meaning you won't have two objects with the same ID in one JSON file)
Every ID will appear in all three lists (meaning you don't need to handle missing fields in output)
/* Again handwaving past loading JSON strings and parsing
them into javascript objects, we'll just start with
three arrays: */
var input1 = [{
"id": "265",
"title": "Battle of Gettysburg",
"page_id": "4849",
"language_id": "en",
"original_time": "July 1\u20133, 1863"
},
{
"id": "1",
"title": "Foo",
"page_id": "123",
"language_id": "en",
"original_time": "July 1\u20133, 1863"
}
];
var input2 = [{
"id": "1",
"original_name": "Bar",
"country_id": "24",
"article_id": "265"
},
{
"id": "265",
"original_name": "United States",
"country_id": "24",
"article_id": "265"
}
]
var input3 = [{
"id": "1",
"month": "July",
"year": "Baz",
"suffix": "",
"article_id": "265"
},
{
"id": "265",
"month": "July",
"year": "1863",
"suffix": "",
"article_id": "265"
}
]
/* It would be much easier to find corresponding IDs
across these arrays if they weren't arrays. We'll
start by converting them into objects keyed by the
item ids: */
var convertArray = function(arr) {
var output = {};
arr.forEach(function(o) {
output[o.id] = o;
});
return output;
}
var obj1 = convertArray(input1);
var obj2 = convertArray(input2);
var obj3 = convertArray(input3);
/* Now if we need to find (say) the object with id "foo", we don't
need to search the whole array, but can just use `obj1["foo"]` or
`obj1.foo`.
The last step is to iterate over the list of IDs and repeatedly
do basically the same thing as in the "if you have three objects"
part above. The only difference is that we need to access the
object with the same ID in each of the input lists: */
var constructOutput = function(in1, in2, in3) {
var output = []; // we'll be outputting a list of objects again.
// step through every ID (assuming in1 contains all of them):
Object.keys(in1).forEach(function(id) {
var obj = {
id: id,
title: in1[id].title,
original_name: in2[id].original_name,
year: in3[id].year
}
output.push(obj);
});
return output;
}
var final = constructOutput(obj1, obj2, obj3)
console.log(final)
Essentially what you have to do is mimic a SQL JOIN using JavaScript objects:
Use JSON.parse() on all three JSON collections to turn them into arrays of objects.
Iterate through JSON 1 objects; for each object...
Iterate through JSON 2 objects, testing if article ID matches the ID from JSON 1 that we are iterating over. Save this object.
Iterate through JSON 3 objects, testing if ID matches the ID of the object we found from JSON 2. Save this object.
After you have all three objects, make a new object literal that contains only the fields you want:
{
Id: obj1.id,
Title: obj1.title,
Original_name: obj2.original_name,
Year: obj3.year
}
Should you want to combine n number of JSON objects, e.g. a list of objects you can take a functional approach and utilise reduce + filter.
const data = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
},
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}];
const final = data.reduce((accu, { id, title }, index, array) => {
// Find any related objects
const matches = array.filter(data => data.article_id === id);
if (matches.length) {
// Flatten them for ease of access. Duplicate keys will override.
const flat = matches.reduce((arr, item) => ({ ...arr, ...item }), [])
// Return new object
return accu.concat({
...flat,
id,
title,
});
}
return accu;
}, []);
console.log(final, '<<')
// Witness
document.getElementById('results').innerHTML = JSON.stringify(final);
<div id="results" style="font-family: Courier; font-size 14px; color: #fff; background: #000; padding: 20px; max-width: 80vw;"></div>
Edited*
Maybe this is what you need?
let arrPages = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
}];
let arrArticles = [{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}];
let getResult = (arrInput, arrCompare) => {
let joinedItems = [];
arrInput.forEach(item => {
let newItem = { id: item.id, title: item.title };
arrCompare.forEach(subItem => {
if(subItem.article_id !== undefined && subItem.article_id === item.id){
if(subItem.original_name !== undefined)
newItem.original_name = subItem.original_name;
if(subItem.year !== undefined)
newItem.year = subItem.year;
}
});
joinedItems.push(newItem);
});
return joinedItems;
};
let result = getResult(arrPages, arrArticles);
console.log(result);
In the first part of the code i create a var that has the json data.
To solve the problema i create 2 functions, the order of the creation dosen't metter, the first function getJSONData() take the json data as parameter and return a object filtered by the keys defined in the array keys. The secound function just check if the current key is present in the array of keys, this function could be replaced by the jQuery.inArray() method.
// JSON data
var json = [{
"id":"265",
"title":"Battle of Gettysburg",
"page_id":"4849",
"language_id":"en",
"original_time":"July 1\u20133, 1863"
},
{
"id":"185",
"original_name":"United States",
"country_id":"24",
"article_id":"265"
},
{
"id":"73",
"month":"July",
"year":"1863",
"suffix":"",
"article_id":"265"
}]
// keys that i want
var keys = ["title", "original_name", "year"];
// var that will have the filtered data
var newJSON = getJSONData(json);
console.log(JSON.stringify(newJSON))
// this is the main function of the code
// here we iterate in the json creating a new object that has all the tags definid in the keys array
function getJSONData(arrayJSON){
var JSONFiltered = {};
for(var i in arrayJSON){
for(var key in arrayJSON[i]){
if(hasElement(key)){
JSONFiltered[key] = arrayJSON[i][key];
}
}
}
return JSONFiltered;
}
// this function is used to check a key is present in the array of keys
function hasElement(key){
for(var elem in keys){
if(keys[elem] == key) return true;
}
return false;
}

make sure values in array are unique when pushing

I push in values from JSON into a several arrays using Underscore, but I want to eliminate any repeated values if there are any, either during push or after. How could I do this?
JSON
looks = [{
"id": "look1",
"products": ["hbeu50271385", "hbeu50274296", "hbeu50272359", "hbeu50272802"]
}, {
"id": "look2",
"products": [
"hbeu50274106", "hbeu50273647", "hbeu50274754", "hbeu50274063", "hbeu50274911", "hbeu50274106", "hbeu50240022", "hbeu50271944"
]
}, {
"id": "look3",
"products": [
"hbeu50272935", "hbeu50274426", "hbeu50271624", "hbeu50274762", "hbeu50275366", "hbeu50274433", "hbeu50262002", "hbeu50272364", "hbeu50272359"
]
}
.......
]
JS (Underscore)
var productArrays = [];
_.each(looks, function(look) {
var productArray = [];
_.each(look.products, function(product) {
productArray.push(product.replace(/_.*/, ''))
})
productArrays.push(productArray);
});
There are couple ways
1.Use _.uniq
_.uniq(productArray);
2.Use _.indexOf before push to productArray
Example
For array's content be unique, how about using _.uniq?
Or just check existence of value before really push it.
function uniquePush(arr, valueToPush) {
if(arr.indexOf(valueToPush) == -1) {
arr.push(valueToPush)
}
}

Accessing JSON array's through object properites

Let's say I have the next JSON file:
{
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
}
I want to access the rating of a show, by it's name. Something like this:
var rating = data.shows["House of cards"].rating;
Is this possible? Or something similar?
Thanks a lot!
You won't have such hash-style access just by deserializing that JSON sample.
Maybe you might be able to re-formulate how the data is serialized into JSON and use object literals even for shows:
{
"shows": {
"House of cards": {
"rating": 8
}
}
}
And you can still obtain an array of show keys using Object.keys(...):
Object.keys(x.shows);
Or you can even change the structure once you deserialize that JSON:
var x = { shows: {} };
for(var index in some.shows) {
x.shows[some.shows[index].name] = { rating: some.shows[index].rating };
}
// Accessing a show
var rating = x.shows["House of cards"].rating;
I suggest you that it should be better to do this conversion and gain the benefit of accessing your shows using plain JavaScript, rather than having to iterate the whole show array to find one.
When you use object literals, you're accessing properties like a dictionary/hash table, which makes no use of any search function behind the scenes.
Update
OP has concerns about how to iterate shows once it's an associative array/object instead of regular array:
Object.keys(shows).forEach(function(showTitle) {
// Do stuff here for each iteration
});
Or...
for(var showTitle in shows) {
// Do stuff here for each iteration
}
Update 2
Here's a working sample on jsFiddle: http://jsfiddle.net/dst4U/
Try
var rating = {
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
};
rating.shows.forEach(findsearchkey);
function findsearchkey(element, index, array) {
if( element.name == 'House of cards' ) {
console.log( array[index].rating );
}
}
Fiddle
var data = {"shows": [{"name": "House of cards","rating": 8},{"name": "Breaking bad","rating": 10}]};
var shows = data.shows;
var showOfRatingToBeFound = "House of cards";
for(var a in shows){
if(shows[a].name == showOfRatingToBeFound){
alert("Rating Of "+ showOfRatingToBeFound+ " is " +shows[a].rating);
}
}

Parse JSON with jQuery

I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?
[
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
]
So far I have:
$.each(test, function(i,item){
alert(item);
});
But that simply lists every value. How can I
That'll list every object in your array, to get the id property of the one you're on, just add .id like this:
$.each(test, function(i,item){
alert(item.id);
});
If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.
If test is written like this:
var test = [
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
];
...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:
$.each(test, function(outerKey, outerValue) {
// At this level, outerKey is the key (index, mostly) in the
// outer array, so 0 or 1 in your case. outerValue is the
// object assigned to that array entry.
$.each(outerValue, function(innerKey, innerValue) {
// At this level, innerKey is the property name in the object,
// and innerValue is the property's value
});
});
Live example

Categories