How to create JSON using Javascript with sets of data? - javascript

I know that I can create this JSON:
[
{
"Title": "Something",
"Price": "234",
"Product_Type": "dsf sf"
},
{
"Title": "hskiuea",
"Price": "4234",
"Product_Type": "sdawer"
}
]
*It uses the values obtained from text inputs contained within an element with the class "newpappend" - As shown below
Using the following code which obtains values from my HTML:
var jsonObj = []; //declare array
$(".newpappened").each(function () {
var p_title = $(this).find('#p_title').val();
var p_price = $(this).find('#p_price').val();
var p_ptype = $(this).find('#p_ptype').val();
jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype});
$(this).remove();
});
But, my goal is to end up with the JSON structured like this:
{
"Product_List": {
"Product": [
{
"Title": "asdf",
"Price": "53",
"Product_Type": "Adfsdf"
},
{
"Title": "asgsd",
"Price": "123",
"Product_Type": "Ntohig"
}
]
}
}
Basically, I am struggling with the correct Javascript to use to reach my goal

You are really close. Start with what you have, and then later:
var output = {
"Product_List": {
"Product": jsonObj
}
}
// output is now what you are looking for.

Related

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"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.

Creating an new object from an existing object in javascript

I am going through a challenge from devchallenges.io, Shoppingify challenge. Having read the prompt, I proceeded to create a model which has the following format when a request is made.
{
"user": 1,
"_id": 3393220221,
"name": Chicken,
"category": "Meat",
"note": "This is an example note",
"image_url": "www.exampleurl.com"
}
The issue I'm having is that the component expects the object in the following format.
{
"category": "Meat",
"items": [
{
"user": 1,
"_id": "3393220221",
"name": "Chicken",
"note": "This is an example note",
"image_url": "www.exampleurl.com"
}
]
}
The link to the challenge is https://devchallenges.io/challenges/mGd5VpbO4JnzU6I9l96x for visual reference.
I'm struggling with how to modify the object response from the request. I want to be able to find occurances of the same category name and push the items onto a new object as shown.
const users = [
{
"user": 1,
"_id": 3393220221,
"name": "Chicken",
"category": "Meat",
"note": "This is an example note",
"image_url": "www.exampleurl.com"
}
];
function modifyUserObject(users) {
const result = {};
users.forEach(user => {
if (!result[user]) {
result[user] = {
category: user.category,
items: []
}
}
//code here..if want to remove user properties like user
result[user].items.push(user);
});
return Object.values(result);
}
modifyUserObject(users);
Hope this will be helpful! Happy coding...
The value Chicken is not defined. Is this a typing error by you? Anyway this should do the trick:
const obj = {
user: 1,
_id: 3393220221,
name: "Chicken",
category: "Meat",
note: "This is an example note",
image_url: "www.exampleurl.com",
};
function createObj(arg) {
let result = {
category: arg.category,
items: [
{
user: arg.user,
_id: arg._id,
name: arg.name,
note: arg.note,
image_url: arg.image_url,
},
],
};
return result;
}
console.log(createObj(obj));
Edit:
If you want to create a new object that is not related to the old one (deep copy) you need to do JSON.parse(JSON.stringify(obj)) to not change the values of the original object.

Updating MongoDB nested array using same path as the search query

I have the following problem, I want to update a document with a path id.metadata.panels.items where panels is an array and items is an array. My search query looks at the items and displays only those that match the criteria of metadata.panels.items.member.type: 'owner' - then I want to update the 'owner to 'account'.
When I am trying to update having the search path same as update path I get an error message saying: cannot use the part metadata.panels.items.member.type to traverse the element.
The documents have their own
How can I resolve this problem?
I have already tried to go through the collection using nested forEach statements to iterate through each of the arrays but I am not sure what to do next.
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
var newFields = [];
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
})
})
})
Sample document structure:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Owner]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
Expected result:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Account]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
I figured it out.
var newFields = [];
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
// I have generated update statements as strings
// first list is always position 0 and this goes to the statement
// second list get's populated from itemIndex
// added them to the newFields list
})
})
})
newFields.forEach(function(i){
eval(i)
})

How to get specific array from JSON object with Javascript?

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.

Printing JSON properties

I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is
[
{
"lang_code": "eng",
"site_language": "1",
"name": "English"
},
{
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
},
{
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
},
]
I want to be able to access the lang_code property of every single language and send it. I've tried to use
var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
languageCodes = languageResult[codes];
}
Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?
On a side note, I also want people to be able to type "! languages [my command] eng", for example, and it sends "English" instead of just sending "1 is [object Object]".
Assuming body is the array at the top of your question, if you just want an array of all the language codes, this should suffice
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
var body = [{
"lang_code": "eng",
"site_language": "1",
"name": "English"
}, {
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
}, {
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
}];
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
document.getElementById('out').innerHTML = JSON.stringify(languageCodes);
<pre id="out"></pre>
I looped through your lang_codes like this:
var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];
for(var i = 0; i < codes.length; i++) {
console.log(codes[i].lang_code);
}

Categories