I need to convert JSON object into different format.
My JSON looks like this -
{
"approver": [
{
"roleId": "New Approver",
"level": "1",
"firstName": "Alan"
},
{
"roleId": "New Approver",
"level": "2",
"firstName": "Alex"
},
{
"roleId": "New Approver",
"level": "1",
"firstName": "Mike"
},
{
"roleId": "USFA",
"level": "1",
"firstName": "Matt"
},
{
"roleId": "USFA",
"level": "1",
"firstName": "John"
}
]
}
Expected output:
Output = [
{ roleName : "New Approver",
levels : [
{ level : "1",
users : ["alan", "mike"] },
{ level : "2",
users : ["alex"] }
] },
{ roleName : "USFA",
levels : [
{ level : "1",
users : ["matt", "john"]
}]
}]
I have tried using reduce function but it does not give me expected results. Could anyone help me convert the object?
Thanks
How about try like Array.from(JSON_object_here)
Related
In my API im receiving a JSON with 2 arrays, one Employees and another with Managers, the goal is to add the Managers to each Employee, knowing that the 1st index of the managers corresponds to the 1st index of the employees and so on:
This is an example of the request to the API
{
"employees" : [ {
"code" : "111111",
"name" : "Zé"
},
{
"code" : "222222",
"name" : "João"
},
{
"code" : "444444",
"name" : "António"
}],
"managers" : [
[
{
"name": "vitor",
"level" : "1"
},
{
"name": "Antonio",
"level" : "2"
}
],
[
{
"name": "Jose",
"level" : "1"
},
{
"name": "Ines",
"level" : "2"
}
],
[
{
"name": "Luis",
"level" : "1"
},
{
"name": "Ana",
"level" : "2"
}
]
]
}
and my goal is to get something like this:
[
{
"code": "111111",
"name": "Zé",
"managers": [
{
"name": "vitor",
"level": "1"
},
{
"name": "Antonio",
"level": "2"
}
]
},
{
"code": "222222",
"name": "João",
"managers": [
{
"name": "Jose",
"level": "1"
},
{
"name": "Ines",
"level": "2"
}
]
},
{
"code": "444444",
"name": "António",
"managers": [
{
"name": "Jose",
"level": "1"
},
{
"name": "Ines",
"level": "2"
}
]
}
]
I already tried some things but i can't get the expected result :(
Hope you can help me!! Thanks
function associate_employee_managers({ employees, managers }) {
return employees && employees.length
&& employees
.map((emp, index) => {
return {
...emp,
["managers"]: managers && managers[index] || []
};
}) || {};
}
Considerations
There is 1-1 correspondence(based on index) between entries inside employees array and managers array
Illustration
function associate_employee_managers({
employees,
managers
}) {
return employees && employees.length &&
employees
.map((emp, index) => {
return {
...emp,
["managers"]: managers && managers[index] || []
};
}) || {};
}
const jsonResponse = {
"employees": [{
"code": "111111",
"name": "Zé"
},
{
"code": "222222",
"name": "João"
},
{
"code": "444444",
"name": "António"
}
],
"managers": [
[{
"name": "vitor",
"level": "1"
},
{
"name": "Antonio",
"level": "2"
}
],
[{
"name": "Jose",
"level": "1"
},
{
"name": "Ines",
"level": "2"
}
],
[{
"name": "Luis",
"level": "1"
},
{
"name": "Ana",
"level": "2"
}
]
]
}
console.log(associate_employee_managers(jsonResponse));
WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET
I'm trying to search through a JSON object to find the pet-rock that I want to delete. Here is a simple JSON that I'm working on:
myData.json:
{
"data": [
{
"name": "John",
"age": "25",
"pet-rocks": [
{
"name": "Travis",
"age": "9"
},
{
"name": "Steven",
"age": "5"
},
{
"name": "Oliver",
"age": "7"
}
]
},
{
"name": "Jane",
"age": "25",
"pet-rocks": [
{
"name": "Jesse",
"age": "4"
},
{
"name": "Carol",
"age": "8"
},
{
"name": "Jake",
"age": "7"
}
]
}
]
}
I would like to do a search for "Steven" and remove that pet-rock from the list. Here are the things I've tried:
MyJSFile.js:
const myDataObject = require('./myData.json');
for (let key in myDataObject) {
let value = myDataObject[key];
if (value === "Steven")
{
delete myDataObject[key];
}
//To see if I get the data I want
console.log(key, value);
}
However, my output is strange and I'm not sure how to get to that child node of petrock. It appears that the petrocks are in object form, and I'm not sure how to get to them. here is the ouput of my console below. I assume it didn't get delete as there are still 3 petrock objects in the data.
data [
{
name: 'Robert',
age: '25',
'pet-rocks': [ [Object], [Object], [Object] ]
},
{
name: 'Robert',
age: '25',
'pet-rocks': [ [Object], [Object], [Object] ]
}
]
Any help or suggestions would be greatly appreciated! Thanks!
The pet rock named Steven is not a direct child of myDataObject, so you can't delete it like that. You can loop through the "data" array, rebuilding the "pet-rocks" array for each element. A simple filter to remove any pet rocks named Steven should work.
const myDataObject = {
"data": [
{
"name": "John",
"age": "25",
"pet-rocks": [
{
"name": "Travis",
"age": "9"
},
{
"name": "Steven",
"age": "5"
},
{
"name": "Oliver",
"age": "7"
}
]
},
{
"name": "Jane",
"age": "25",
"pet-rocks": [
{
"name": "Jesse",
"age": "4"
},
{
"name": "Carol",
"age": "8"
},
{
"name": "Jake",
"age": "7"
}
]
}
]
};
myDataObject.data.forEach(d => {
d["pet-rocks"] = d["pet-rocks"].filter(rock => rock.name !== "Steven");
});
console.log(myDataObject);
I've been playing around trying to learn in an API project using Postman and conducting tests using JavaScript. So far, I have succeeded with the help of reading on websites and watching YouTube videos. Of course, previous tests and playing around have been fairly easy but now I came to a stop. I really tried to figure this out for several weeks but I need further guidance, a push in the right direction or direct help.
What I'm trying to do is to filter out some of the response to only view objects that contain specific data.
To do that, I'm using a filter where I want all products containing a specific value inside an array "product_option_values".
My first approach was to see if I could sort products having any values from the first array, and it worked. It filters just fine.
var filterSmall = jsonData.products.filter(fs => fs.associations.product_option_values);
My next approach was to get to my goal of filtering out products according to specific values inside this array. I tried many simple .(dot) combinations and pointing to [index] to access it without any luck. (I must add that I know how to access this from a specific product, but that way doesn't work when filtering).
I've also tried other approaches such as:
var filterSmall = jsonData.products.filter(fs => fs.associations["product_option_values", 0, "name"] === "S");
and other similar combinations.
This is a very shortened sample of the structure of "products" which in its full form consists of 20 products and far more values inside of it:
{
"products": [
{
"id": 16,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Mountain fox notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "22"
},
{
"id": "23"
}
]
}
},
{
"id": 17,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Brown bear notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "23"
},
{
"id": "24"
}
]
}
}
]
}
and here is a small and expanded sample from product_option_values:
{
"product_option_values": [
{
"id": 1,
"id_attribute_group": "1",
"color": "",
"position": "0",
"name": "S"
},
{
"id": 2,
"id_attribute_group": "1",
"color": "",
"position": "1",
"name": "M"
},
{
"id": 3,
"id_attribute_group": "1",
"color": "",
"position": "2",
"name": "L"
}
]
}
How do I proceed? Did I do anything correct or even close to it?
Perhaps I've been staring at this for too long.
Thanks in advance.
If you want to compare nested attributes you have to transform the objects (e.g. by using a map operation), so that the relevant attributes are easily accessible for a comparison. If you want to filter by product_option_value id, you could do something like this:
const jsonData = {
"products": [
{
"id": 16,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Mountain fox notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "22"
},
{
"id": "23"
}
]
}
},
{
"id": 17,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Brown bear notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "23"
},
{
"id": "24"
}
]
}
}
]
};
const sample = {
"product_option_values": [
{
"id": 22,
"id_attribute_group": "1",
"color": "",
"position": "0",
"name": "S"
},
{
"id": 2,
"id_attribute_group": "1",
"color": "",
"position": "1",
"name": "M"
},
{
"id": 3,
"id_attribute_group": "1",
"color": "",
"position": "2",
"name": "L"
}
]
};
const ids = sample.product_option_values.map((el) => String(el.id));
console.log(ids);
const filtered = jsonData.products.filter((fs) => fs.associations.product_option_values.map((e) => e.id).some((f) => ids.includes(f)));
console.log(filtered);
I need help regarding rendering this JSON data in html table using angular:
[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}]
My rendered html table should look like this
Test1 Test2
John 20 50
Doug 10 100
Somehow values need to be grouped by, and then rendered, but to keep matching data. Also that first position in array[0][0] should be empty. Any help will be appreciated.
So you can group your data by name , and have Object of arrays like following :
{
"John": [
{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test2",
"number": 50,
"name": "John"
}
],
"Doug": [
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}
]
}
Then , define a function to retrieve data by name & task : getItemBy=function(name,task)
Those two steps will make your algo easy to render HTML table as u want :
DEMO :
var data=[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}];
var groupBy=function(arr,key) {
return arr.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
//------
var groupedByName=groupBy(data,'name');
var getItemBy=function(name,task){
return groupedByName[name].filter((item)=>item.task===task)
};
//------
//--
console.log(`***** Item where name=John & task=Test1`,
getItemBy('John','Test1')
)
console.log(`****** All data after grouping`,
groupedByName
)
I'm planning on using materialized paths in MongoDB to represent a tree and need to convert the materialized paths back into a JSON tree.
ex.
// Materialized path
var input = [
{"id": "0", "path": "javascript" },
{"id": "1", "path": "javascript/database" },
{"id": "2", "path": "javascript/database/tree" },
{"id": "3", "path": "javascript/mvc" },
{"id": "4", "path": "javascript/mvc/knockout.js"},
{"id": "5", "path": "javascript/mvc/backbone.js"},
{"id": "6", "path": "c++" },
{"id": "7", "path": "c++/c0xx"},
{"id": "8", "path": "c++/c0xx/lambda expressions"},
{"id": "9", "path": "c++/c0xx/vc10" }
];
The result would be:
[
{
"id": "0",
"name": "javascript",
"children": [
{
"id": "1",
"name": "database",
"children": [
{
"id": "2",
"name": "tree",
"children": []
}
]
},
{
"id": "3",
"name": "mvc",
"children": [
{
"id": "4",
"name": "knockout.js",
"children": []
},
{
"id": "5",
"name": "backbone.js",
"children": []
}
]
}
]
},
{
"id": "6",
"name": "c++",
"children": [
{
"id": "7",
"name": "c0xx",
"children": [
{
"id": "8",
"name": "lambda expressions",
"children": []
},
{
"id": "9",
"name": "vc10",
"children": []
}
]
}
]
}
]
I found Convert delimited string into hierarchical JSON with JQuery which works fine.
And I also found Build tree from materialized path which is written in Ruby and uses recursion. I'm interested and curious to see this implemented in Javascript and wonder whether there are any folks that are fluent in both Ruby and Javascript who would like to rewrite it. I did try a Ruby to JS converter, but the result was incomprehensible.
Thanks,
Neville
var Comment = new Schema({
date : {
type : Date,
default : Date.now
},
event: ObjectId,
body : String,
pathComment : String,
user: Array
})
Comment.virtual('level').get(function() {
return this.pathComment.split(',').length;
});
Comment.find({event: event.id}).sort({pathComment:1}).exec(function(err, comment){
var collectComment = function(comment){
return {
body: comment.body,
event: comment.event,
pathComment: comment.pathComment,
id: comment._id,
level: comment.level,
user: comment.user[0],
date: comment.date,
comments: []
};
}
var tplComment = [];
var createChildComment = function(comment, currentNode, level){
if(level==1){
comment.push(collectComment(currentNode));
}else{
createChildComment(comment[comment.length-1]['comments'], currentNode,level-1);
}
return;
}
for(var k in comment){
createChildComment(tplComment, comment[k],comment[k].level);
}
});