I'm a beginner in Javascript so please exuse this probably dumb question. I want to merge two json files based on unique object id.
Number one look like this:
"features": [{
"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}},
{"id": "3876803",
"properties": {"name":"another name"...}}...]
Number Two looks like this:
"features": [{
"id": "3876803",
"properties": {
"description": "some description",
"website": "afancywebsite"}},
{"id": "3876803",
"properties": {...}}]
The Elements in the second Json are not in the same order and not all elements of the first file exist in the second.
The Result should look like this:
"features": [{
"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}},{
"id": "3876803",
"properties": {
"name":"another name",
"description": "some description",
"website": "afancywebsite"}}]
I started coding this but I have no idea how to get it working...
for(var i in json1.features){
for (var z in json2.features){
if (json1.features[i].id===json2.features[z].id){
json1.feature[i].properties = json2.features[z].properties}}}
This will do the job:
var features = [
{"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}
},
{"id": "3876803",
"properties": {
"name":"another name"
}
}
];
var features2 = [{
"id": "3876803",
"properties": {
"description": "some description",
"website": "afancywebsite"
}
}
];
features.map(function(feature){
var matchedArray = features2.filter(function(feature2){
return feature2.id === feature.id;
});
if(matchedArray && matchedArray[0]){
for(var attr in matchedArray[0].properties){
feature.properties[attr] = matchedArray[0].properties[attr];
}
}
});
We start by using Array.map() to run through the 'features' array, one by one.
Then we use Array.filter() on the features2 array which gives us an array containing the only object in features2 (matched[0]) which has the same id as feature.id.
If there's a match, then we run through the 'properties' in the features2 object using a 'for in' loop and copy them to the 'feature' object.
If you want to get advanced info about this check out this stackoverflow question: How can I merge properties of two JavaScript objects dynamically?. For example, if you're writing bullet-proof javascript you should use 'hasOwnProperty' in a for in loop.
You may also want to guard against properties in 'features2' overwriting a property with the same name in 'features'.
However if you would like to keep your code more or less as it was this also works:
for(var i in features){
for (var z in features2){
if (features[i].id===features2[z].id){
for(var attr in features2[z].properties){
features[i].properties[attr] = features2[z].properties[attr];
}
}
}
}
Related
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.
I receive with my ajax post request a message with values to display. This json response message looks like this:
{
"line": {
"name": "Google item",
"images": {
"element": {
"order": "1",
"link": "https://google.com/1.jpg",
"name": "1.jpg"
},
"element": {
"order": "2",
"link": "https://google.com/2.jpg",
"name": "2.jpg"
},
"element": {
"order": "3",
"link": "https://google.com/3.jpg",
"name": "3.jpg"
},
"element": {
"order": "4",
"link": "https://google.com/4.jpg",
"name": "4.jpg"
},
"element": {
"order": "5",
"link": "https://google.com/5.jpg",
"name": "5.jpg"
}
},
"features": {
"element": {
"name": "1",
"order": "1"
},
"element": {
"name": "2",
"order": "2"
},
"element": {
"name": "3",
"order": "3"
},
"element": {
"name": "4",
"order": "4"
}
},
"purchasing_price": "10",
"selling_price": "20",
"ftp_path": "google/item",
"description": ""
}
}
I'm in development and have not so much experience with json in jquery/ajax.
I tried this:
function parseContent(content){
$("#name").val(content.line.name);
$("#ftp_path").val(content.line.ftp_path);
$("#html_description").val(content.line.description);
$("#feature").remove();
$.each(content.line.features, function(k, v){
$("#features").append('<input type="text" class="form-control mt-3" id="feature" value="' + v.name + '" required>');
alert(v.name );
});
}
My problem is, the variable content contains just the last image und feature element. But in chrome/network I could see, the complete message has been received.
So I found out there is a parsing issue: Parsed JSON contains only the last element.
But how can I fix this in my case, to iterate through all elements?
The JSON specification says:
The names within an object SHOULD be unique.
The names in those objects are not.
SHOULD means:
that there
may exist valid reasons in particular circumstances to ignore a
particular item, but the full implications must be understood and
carefully weighed before choosing a different course.
The implications here are that every JSON parser (that I'm aware of at least) will ignore all but one of the values with duplicate names in an object.
If you really need to deal with that data then you are going to have to either track down a parser which can handle it (I'm not aware of any) or write a custom JSON parser which can (you'll also need to decide what data structure you want to generate from it because JS can't have duplicate property names in objects either). There are a number of JSON parsers on npm you might want to examine the source code of as a starting point.
A better solution would be to change whatever is generating the source data to produce a sensible format that doesn't violate a SHOULD requirement. Replacing the duplicate property names with an array for example.
I have a huge static JSON file that contains all champions in a certain game and some information about them. Currently, I need to figure out how to find the champion object whose "key" property is 266. Sadly I'm having some difficulty figuring out how to get that object. I assume I have to loop through the objects, however, usually when I loop through something, it's an array but this is not the case.
I've put a simplified example of the json structure below. I have an integer 266 and now I need to somehow access the object with "key": "266" which would be Aatrox. Any clues on how would I do that?
"data": {
"Aatrox": {
"version": "8.19.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "8.19.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
}
}
You can use find
Get the entries from data key using Object.entries
Find value whose key property is equal to our desired key using find
let obj = {"data": {"Aatrox": {"version": "8.19.1","id": "Aatrox","key": "266","name": "Aatrox","title": "the Darkin Blade"},"Ahri": {"version": "8.19.1","id": "Ahri","key": "103","name": "Ahri","title": "the Nine-Tailed Fox"}}}
let findByKey = (matchKey) => Object.entries(obj.data).find(([key,value]) => value.key === matchKey)
console.log(findByKey('266'))
Here's a generic function you can use to search for any key and value:
const obj = {"data": {"Aatrox": {"version": "8.19.1","id": "Aatrox","key": "266","name": "Aatrox","title": "the Darkin Blade"},"Ahri": {"version": "8.19.1","id": "Ahri","key": "103","name": "Ahri","title": "the Nine-Tailed Fox"}}}
const searchKeyValue = {key:"key", value:"266"}
const search = data => skv => Object.entries(data).filter(([key,value])=>value[skv.key]===skv.value)
console.log(search(obj.data)(searchKeyValue))
So you can find via e.g. searchKeyValue = {key:"id", value:"Ahri"} or whatever you like.
You could also use JSONPath i.e.
$..data[?(#.key==266)]
Assuming :
{"data": {
"Aatrox": {
"version": "8.19.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "8.19.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
}
}
}
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I have a TopoJSON file with several geometries. It looks like so:
{
"type": "Topology",
"objects": {
"delegaciones": {
"geometries": [
{
"properties": {
"name": "Tlalpan",
"municip": "012",
"id": "09012",
"state": "09"
}
...
I want to be able to take the id field from properties, and assign it to the parent, so that the result is:
{
"type": "Topology",
"objects": {
"delegaciones": {
"geometries": [
{
"id": "09012",
"properties": {
"name": "Tlalpan",
"municip": "012",
"id": "09012", // <-- It's okay if it's removed or not
"state": "09"
}
...
I tried the following assignment on jq, but it's not correct:
jq '.objects.delegaciones.geometries[].id = .objects.delegaciones.geometries[].properties.id' topo_df.json
Anyone know how I can make jq iterate elements one by one? Or how I can make this work?
The following adds the "id" property as requested:
.objects.delegaciones.geometries[] |= (.id = .properties.id)