Related
I am new to node.js and javascript. I am trying to build a rest API.
For a specific purpose, I need to convert an object to 3d array.
I tried running for, foreach loop but it is not providing what I am trying to achieve.
My object looks like this.
"data": [
{
"id": 15184,
"badge_id": "330886",
"name": "Rukmani J. Solanki",
"gender": "Female",
"type": "PF",
"department": "Sales",
"checkin": "2021-09-24T08:52:44.000Z",
"checkout": "2021-09-24T08:57:45.000Z",
"hours": "00:05"
},
{
"id": 15185,
"badge_id": "440886",
"name": "Jairam J. Solanki",
"gender": "Male",
"type": "PM",
"department": "Sales",
"checkin": "2021-09-24T09:28:32.000Z",
"checkout": null,
"hours": null
}
]
And I want something like this
{
"onfield": [
{
"key": "Sales",
"data": {
"PM": [
{
"name": "Gokuldas S. Sundrani",
"badge_id": "441101",
"gender": "Male",
"checkIn": "2021-09-24 06:04:18",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "551249",
"gender": "Male",
"checkIn": "2021-09-24 06:47:31",
"checkOut": "2021-09-24 08:32:00",
"hours": "1.7 Hours"
},
{
"name": "Praveen N. Jethwani",
"badge_id": "771328",
"gender": "Male",
"checkIn": "2021-09-24 07:14:11",
"checkOut": "2021-09-24 08:29:34",
"hours": "1.3 Hours"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "88249",
"gender": "Male",
"checkIn": "2021-09-24 08:32:00",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Arjundas D. Chhabra",
"badge_id": "661248",
"gender": "Male",
"checkIn": "2021-09-24 10:19:22",
"checkOut": "2021-09-24 18:38:32",
"hours": "8.3 Hours"
},
{
"name": "Parmanand C. Lalwani",
"badge_id": "8651418",
"gender": "Male",
"checkIn": "2021-09-24 14:51:08",
"checkOut": "2021-09-24 17:39:27",
"hours": "2.8 Hours"
},
{
"name": "Dhanalal G. Chouhan",
"badge_id": "5501392",
"gender": "Male",
"checkIn": "2021-09-24 14:58:46",
"checkOut": "2021-09-24 18:20:50",
"hours": "3.4 Hours"
}
],
"PF": [
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "501993",
"gender": "Female",
"checkIn": "2021-09-24 06:47:48",
"checkOut": "2021-09-24 08:32:12",
"hours": "1.7 Hours"
},
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "801993",
"gender": "Female",
"checkIn": "2021-09-24 08:32:12",
"checkOut": null,
"hours": "NoCheckOut"
}
],
"OM": [
{
"name": "Yadvendra Bhati",
"badge_id": "2255454",
"gender": "male",
"checkIn": "2021-09-24 13:38:37",
"checkOut": "2021-09-24 17:24:11",
"hours": "3.8 Hours"
}
],
"OF": [
{
"name": "Yashoda Bhati",
"badge_id": "223F0029",
"gender": "Female",
"checkIn": "2021-09-24 13:38:44",
"checkOut": "2021-09-24 17:24:25",
"hours": "3.8 Hours"
}
]
}
}
]
}
How can this be done?
I will be really grateful to you for your help.
I have googled and searched StackOverflow but did not find anything which deals with this kind of problem.
Thank You
Although I totally agree with Juan Mendes, here is a tip in order for you to be able to accomplish this. You may get an intermediate form for your data as this one:
{
"onfield": [
{
"key": "dept1",
"data": {
"PM": [
{
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male"
}
]
}
},
{
"key": "dept2",
"data": {
"PF": [
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female"
}
]
}
},
{
"key": "dept1",
"data": {
"PM": [
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}
]
}
}
]
}
Perhaps transforming your source data to this one is easier. And getting to your target from here will be just a matter of merging arrays of the same type.
Do not hesitate to ask if this keeps being difficult. But as said, please try to solve this yourself, that's the way you are going to learn.
let data = [{ "id": 123, "badge_id": "1231", "name": "name1", "gender": "Male", "type": "PM", "dept": "dept1" }, { "id": 124, "badge_id": "1232", "name": "name2", "gender": "Female", "type": "PF", "dept": "dept2" }, { "id": 125, "badge_id": "1233", "name": "name3", "gender": "Male", "type": "PM", "dept": "dept1" }];
let Report = []
data.forEach((item) => {
let obj = Report.find(v => v.dept == item.dept);
if (!obj) Report.push(obj = {
dept: item.dept,
type: {}
});
obj.type[item.type] ??= [];
obj.type[item.type].push({
id: item.id,
badge_id: item.badge_id,
name: item.name,
gender: item.gender,
});
})
console.log(Report)
Here's Something i think is more feasible than your result .. Checkout
let myObject = {
"data": [ {
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male",
"type": "PM",
"dept": "dept1"
},
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female",
"type": "PF",
"dept": "dept2"
},
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}]
}
function generateReport(object) {
let obj = {
"Report": []
};
let types = [];
object.data.forEach(arr =>{
if(!types.includes(arr.type)){
types.push(arr.type);
}
});
types.forEach(type =>{
obj.Report.push({
type : type,
users : object.data.filter(arr=>{ let a = arr.type == type;
if(a){
delete arr.type;
}
return a;
})
});
});
return obj;
}
myObject = generateReport(myObject);
console.log(myObject)
You oculd take the wanted grouping keys in an array and destructure the object to remove this keys from the object.
Every key takes it own nested object structure.
const
data = [{ id: 123, badge_id: "1231", name: "name1", gender: "Male", type: "PM", dept: "dept1" }, { id: 124, badge_id: "1232", name: "name2", gender: "Female", type: "PF", dept: "dept2" }, { id: 125, badge_id: "1233", name: "name3", gender: "Male", type: "PM", dept: "dept1" }],
keys = ['dept', 'type'],
result = data
.reduce((r, o) => {
keys
.reduce(function (t, k) {
let key;
({ [k]: key, ...o } = o);
if (!t[key]) t._.push({ [k]: key, data: (t[key] = { _: [] })._ });
return t[key];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Lets suppose I have a JSON ListA:
LIST A
[
{
"address": "wellington lane",
"age": "23",
"country": "Australia",
"name": "Mike",
"profession": "Lawyer"
},
{
"address": "Street 25",
"age": "26",
"country": "New Zealand",
"name": "Parks",
"profession": "Engineer"
},
{
"address": "North cross",
"age": "29",
"country": "Korea",
"name": "Wanda",
"profession": "Doctor"
}
]
LIST B
["name","age","address","country","profession"]
The requirement is I need to sort the JSON LIST A according to the array LIST B and the output should look like:
[
{
"name": "Mike",
"age": "23",
"address": "wellington lane",
"country": "Australia",
"profession": "Lawyer"
},
{
"name": "Parks",
"age": "26",
"address": "Street 25",
"country": "New Zealand",
"profession": "Engineer"
},
{
"name": "Wanda",
"age": "29",
"address": "North cross",
"country": "Korea",
"profession": "Doctor"
}
]
How can I sort this out? I have tried this solution, but it seems this is not working.
Ciao, you could try to iterate in both arrays and create an array result with ordered attributes like this:
let input = [
{
"address": "wellington lane",
"age": "23",
"country": "Australia",
"name": "Mike",
"profession": "Lawyer"
},
{
"address": "Street 25",
"age": "26",
"country": "New Zealand",
"name": "Parks",
"profession": "Engineer"
},
{
"address": "North cross",
"age": "29",
"country": "Korea",
"name": "Wanda",
"profession": "Doctor"
}
]
let fields = ["name","age","address","country","profession"]
let result = [];
input.forEach(el => {
let resultobj = {}
fields.forEach(fi => {
resultobj[fi] = el[fi]
})
result.push(resultobj)
})
console.log(result)
Here's a solution using map and reduce:
const arr = [
{
"address": "wellington lane",
"age": "23",
"country": "Australia",
"name": "Mike",
"profession": "Lawyer"
},
{
"address": "Street 25",
"age": "26",
"country": "New Zealand",
"name": "Parks",
"profession": "Engineer"
},
{
"address": "North cross",
"age": "29",
"country": "Korea",
"name": "Wanda",
"profession": "Doctor"
}
];
const order = ["name", "age", "address", "country", "profession"];
const newArr = arr.map(e => order.reduce((obj, key) => ({ ...obj, [key]: e[key] }), {}));
console.log(newArr);
One way to do this without having to rely on an external library:
const arr = [
{
'address': 'wellington lane',
'age': '23',
'country': 'Australia',
'name': 'Mike',
'profession': 'Lawyer',
},
{
'address': 'Street 25',
'age': '26',
'country': 'New Zealand',
'name': 'Parks',
'profession': 'Engineer',
},
{
'address': 'North cross',
'age': '29',
'country': 'Korea',
'name': 'Wanda',
'profession': 'Doctor',
},
];
const keyOrder = ['name', 'age', 'address', 'country', 'profession'];
function applyKeyOrder(obj, keyOrder) {
const res = {};
for (const key of keyOrder) {
res[key] = obj[key];
}
return res;
}
const result = arr.map(element => applyKeyOrder(element, keyOrder));
console.log(result);
Note that this assumes that all keys in the keyOrder-array actually exist in the objects, i.e. fields would get lost if they're not present in the array.
Where "LIST A" is listA and "LIST B" is listB:
const formatList = () => {
return listA.map(item => {
const res = {};
listB.map(label => {
res[label] = item[label];
})
return res;
})
};
console.log(formatList())
I want to filter objects based on a set of arrays containing filter terms. It basically works until one of the filter arrays contains multiple terms. Here is the code:
// the filters
const filters = {
"eyeColor": ["blue"],
"gender": ["male"],
"age": ["33"],
"tags": ["d3js", "vuejs"] // multiple terms in the filter array breaks the code (returns empty array)
}
// the data
const users = [
{
"age": "33",
"eyeColor": "blue",
"tags": "d3js, max, grotesk",
"gender": "male",
},
{
"age": "31",
"eyeColor": "blue",
"tags": "vuejs, adrian, serif",
"gender": "male",
},
{
"age": "37",
"eyeColor": "brown",
"tags": "vuejs, max, mono, d3js",
"gender": "female",
},
{
"age": "33",
"eyeColor": "blue",
"tags": "vuejs, markus, grotesk",
"gender": "male",
},
]
// the filter function
let results = users.filter(function (object) {
return Object.entries(filters).every(function ([key, value]) {
return value.every(function (filter) {
return object[key].includes(filter)
})
})
});
console.log(results);
I get an empty array, while the expected result would be:
{
"age": "33",
"eyeColor": "blue",
"tags": "d3js, max, grotesk",
"gender": "male",
},
{
"age": "33",
"eyeColor": "blue",
"tags": "vuejs, markus, grotesk",
"gender": "male",
}
How can I get the expected result?
The code uses
return value.every(function (filter) ...
// ^^^^^
but you don't want to match all of the tags in the permitted array, only some (any):
return value.some(function (filter) ...
// ^^^^
Here's a demonstration:
const filters = { "eyeColor": ["blue"], "gender": ["male"], "age": ["33"], "tags": ["d3js", "vuejs"] }
const users = [{ "age": "33", "eyeColor": "blue", "tags": "d3js, max, grotesk", "gender": "male", }, { "age": "31", "eyeColor": "blue", "tags": "vuejs, adrian, serif", "gender": "male", }, { "age": "37", "eyeColor": "brown", "tags": "vuejs, max, mono, d3js", "gender": "female", }, { "age": "33", "eyeColor": "blue", "tags": "vuejs, markus, grotesk", "gender": "male", }, ];
const filterEntries = Object.entries(filters);
const results = users.filter(user =>
filterEntries.every(([key, permitted]) =>
permitted.some(e => user[key].includes(e))
)
);
console.log(results);
in firebase i want to extract data but it returns object inside another object Object {
"-LJFXZDI-O-qR572deOs": Object {
"city": "almaty",
"dob": "1995-08-06",
"gender": "male",
"height": "190",
"userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2",
"username": "aaaa",
"weight": "80",
},
}
i want to get inner object "city": "almaty",
"dob": "1995-08-06",
"gender": "male",
"height": "190",
"userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2",
"username": "aaaa",
"weight": "80",
but i do know this key "-LJFXZDI-O-qR572deOs" what should i do?
Here is how you access the key without knowing the key, using Object.keys:
var obj = {
"-LJFXZDI-O-qR572deOs": {
"city": "almaty",
"dob": "1995-08-06",
"gender": "male",
"height": "190",
"userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2",
"username": "aaaa",
"weight": "80",
},
}
keys = Object.keys(obj); // all keys of the outer object
myKey = keys[0]; // the unknown key of the inner object
innerObject = obj[myKey];
city = innerObject.city;
console.log(city);
You can do:
const obj = {
"-LJFXZDI-O-qR572deOs": {
"city": "almaty",
"dob": "1995-08-06",
"gender": "male",
"height": "190",
"userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2",
"username": "aaaa",
"weight": "80",
}
};
const key = Object.keys(obj)[0];
const city = obj[key].city;
console.log(key);
console.log(city);
I want to make a http request to a url lets say
http://test1.com/info this will give me xml
I want to convert
this xml from 1 to json lets say json 1
Now I make a rest request to url lets
say http://test2.com/myweb this returns a json lets say json 2
json 1
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7"
}
.... some 100 entries
]
and json 2 some like below
[
{
"id": "123",
"country": "USA",
"state": "KA",
"age": 24,
"group": "g1"
}
{
"id": "456",
"country": "UK",
"state": "MA",
"age": 28,
"group": "G2"
}
...... 100 entries
]
Now Id is the constant thing between json1 and json2 I want to make a resultant json something like below lets call json3.I want to match the id and get country and state from json2 and append to json1
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6",
"country":"USA",
"state":"KA"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7",
"country":"UK",
"state":"MA"
}
]
Now wat i tried for 1 and 3 but for 2 dont know wat to do and to compare and combine I am not sure wat to do If any help will be greatful
function fun()
{
var data="hello";
$.post('http://localhost/ws/service.asmx/HelloWord',{},function(response)
{ data = response;
}).error(function(){
alert("Sorry could not proceed");
});
return data;
}
you can try this:
<script>
$(document).ready(function(){
var result=[];
var x=[{"id": "123","testname": "test123", "name": "John Doe","active": true,"type": "test6"},{"id": "456", "testname": "test564", "name": "Ship Therasus", "active": true,"type": "test7" }];
var y = [{ "id": "123", "country": "USA", "state": "KA", "age": 24,"group": "g1"},{ "id": "456", "country": "UK", "state": "MA", "age": 28, "group": "G2"}];
for (i in x){
for (j in y){
if(x[i].id == y[j].id){
result.push($.extend(x[i], y[j]));
}
}
}
console.log(result);
});
</script>