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.
Related
I am trying to display my seed data as JSON when a user visits a certain endpoint. I have two tables, Playlists and Favorites. It is a one to many relationship where a Playlist has many Favorites. The JSON should be formatted like this:
[{
"id": 1,
"playlist_name": "Favorite songs of all time",
"favorites": [{
"id": 1,
"name": "We Will Rock You",
"artist_name": "Queen",
"genre": "Rock",
"rating": 88
}]
}]
The function that I am calling to retrieve data from the database is this:
const connection = require("../connection");
function getAll() {
return connection.select().from('playlists').join('favorites', 'playlists.id', '=', 'favorites.id')
}
module.exports = getAll;
And what I get back when I call this function is this:
[
{
"id": 1,
"playlist_name": "chill_tunes",
"name": "Leo",
"artist_name": "John",
"genre": "Pop",
"rating": 42,
"playlist_id": 1
},
{
"id": 2,
"playlist_name": "good_vibes",
"name": "Dan",
"artist_name": "Deer",
"genre": "Rock",
"rating": 52,
"playlist_id": 1
},
{
"id": 3,
"playlist_name": "hump_day_happiness",
"name": "Nick",
"artist_name": "Legend",
"genre": "Rap",
"rating": 12,
"playlist_id": 2
}
]
I have no idea how to format my JSON data to get it like the code up top. Any help would be greatly appreciated.
You can use reduce
Here idea is
On op object create keys based on playlist id.
If there's already a key we push the new value to favourites
If not than we initialize favourites with {id, playlist_name , favourites:[]} and than push the new value
let arr = [{"id": 1,"playlist_name": "chill_tunes","name": "Leo","artist_name": "John","genre": "Pop","rating": 42,"playlist_id": 1},{"id": 2,"playlist_name": "good_vibes","name": "Dan","artist_name": "Deer","genre": "Rock","rating": 52,"playlist_id": 1},{"id": 3,"playlist_name": "hump_day_happiness","name": "Nick","artist_name": "Legend","genre": "Rap","rating": 12,"playlist_id": 2}]
let final = arr.reduce((op,{id, playlist_name ,name ,artist_name ,genre ,rating , playlist_id}) => {
op[playlist_id] = op[playlist_id] || {id, playlist_name , favourites:[]}
op[playlist_id].favourites.push({id, playlist_id ,name ,artist_name ,genre ,rating})
return op
},{})
console.log(Object.values(final))
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 am using Dojox to get an array of objects back that meet an expression, I recently changed my service and now it returns more complicated JSON property banes and my query has stopped working. I think I can place a wild card [*]operator to the start of my query string.
Old JSON
[
{
"attributes": [{
"Type": 1,
"User": "Dave",
"Location": "England"
}]
},
{
"attributes": [{
"Type": 1,
"User": "Paul",
"Location": "England"
}]
},
{
"attributes": [{
"Type": 2,
"User": "James",
"Location": "England"
}]
}
]
Old query string
var jam = dojox.json.query(“[?attributes.Type='0'”, data);
This used to work fine but since the JSON has changed the query isn't working
New JSON
[
{
"attributes": [{
somevalue."sometingelse".username.Type: 1,
somevalue."sometingelse".username.User: "Dave",
somevalue."sometingelse".username.Location: "England",
}]
},
{
"attributes": [{
somevalue."sometingelse".username.Type: 1,
somevalue."sometingelse".username.User: "Paul",
somevalue."sometingelse".username.Location: "England",
}]
},
{
"attributes": [{
somevalue."sometingelse".username.Type: 2,
somevalue."sometingelse".username.User: "Steve",
somevalue."sometingelse".username.Location: "England",
}]
}
]
I have tried with a few variations of a similar query with no success
var jam = dojox.json.query(“[?attributes.*Type='0'”, data);
var jam = dojox.json.query(“[?attributes][*Type='0']”, data);
Happy to give further details, thank you in advance.
Essentially a dodgy join we replaced it with a view and set the field names. Another fix was to rename all the layers in the MXD and republished the ArcGIS service.
var jam = dojox.json.query(“[?attributes.Type='0'”, data);
Would work fine after that.
I know there's plenty of answers on this and most are suggesting looping thru the object, returning what you need, I'm not sure this is the best approach, in my case anyway.
What I have is array with entries referencing to another array people(with id and name) by person_id and projects(with id and name) by project_id.
What I need is to be able to access project and person with a particular id inside the loop on entries, so I can get their names. Doing what others have suggested I'd loop thru people and projects inside each irritation of entries, which seems like awful lot of looping.
So I thought I'd make something I called a "hashtable" from both people and projects on init, which means pretty much creating a new objects people_hashtable and projects_hashtable where key would be the id
so
[
{
"id": "8",
"name": "John Doe"
}
]
would became
{
"8": {
"name": "John Doe"
}
}
this way I'd have easy access to the name without looping all the time while still maintaining the old array with its original order(that's why I'm not outputting it this way directly from server, you can't quite order an object and I'm using both people and projects in a selectbox, which needs to be ordered by name).
Am I doing it right? Are there better way? Or should I forget this completely and stick with the search loop as suggested in other question?
I'm trying to be as efficient as possible on both server and client side.
You basically doubled all the objects just to avoid loop. So, unless you have some bad performance issues, I would avoid that.
In case you really, really need a kind of hashmap, I would prefer storing the array's index instead of another copy of the object:
// array
var arr = [
{
"id": "8",
"name": "John Doe"
}
];
// lookup table
var lookup = {
"8": 0
}
Of course doing that, means you can't modifying the array's without rebuild the hashmap.
Generate it's quite simple:
var lookup = arr.reduce(function(lookup, item, index) {
lookup[item.id] = index;
return lookup;
}, {});
You can also use that to generate the object you mentioned your question:
var lookup = arr.reduce(function(lookup, item) {
lookup[item.id] = {name: item.name};
return lookup;
}, {});
But as I said it's something I would avoid.
Following code may help you. JSFIDDLE
var arr = [
{
"id": "8",
"name": "John Doe"
}
];
var obj = {};
for(var i=0; i< arr.length; i++){
obj[arr[i].id] = {name: arr[i].name};
}
console.log(obj);
var articles= {
"item1":{
"id":"155",
"name":"First Item",
"value":-5199.6
},
"item2":{
"id":"255",
"name":"Second Item",
"value":-424.91
}
}
var ids = [];
for(var item in articles) {
ids.push(articles[item]['id']);
}
console.log(ids);
This lib https://github.com/paularmstrong/normalizr makes it pretty easy to do. Both normalization and denormalization.
It can turn this
{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
into this
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
and the other way around.
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.