process array of objects [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have this code,
"data": [
{
"pid": 1,
"status": "done",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "21"
},
{
"pid": 2,
"status": "pending",
"title": "c"
}
]
I am trying to process it like this
"data": [
{
"pid": 1,
"done": 1,
"pending":2
},
{
"pid": 2,
"done": 0,
"pending":1
}
]
I have tried much to produce my desired results but no luck, now i m posting here to get some help.
thanks

You should be able to use Array.reduce for this purpose.
We create a map, keyed by pid then add 1 for each done or pending object.
Object.values will then turn this map into an array again.
I hope this helps you!
data = [
{
"pid": 1,
"status": "done",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "21"
},
{
"pid": 2,
"status": "pending",
"title": "c"
}
]
let result = Object.values(data.reduce( (map, d) => {
if (!map[d.pid]) map[d.pid] = { pid: d.pid, done: 0, pending: 0 };
if (d.status === "done") map[d.pid].done++;
if (d.status === "pending") map[d.pid].pending++;
return map;
}, {} ));
console.log("Result:", result);

Related

How to convert array to single object? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I have array object like this.
[
{
"name": "name1",
"type": "type1",
"car": "car1",
"speed": 1
},
{
"name": "name1",
"type": "type1",
"car": "car2",
"speed": 2
},
]
And i want to convert it single object for prevent data replay.
How can i do this?
{
"name": "name1"
"type": "type1",
"car": [
"car1",
"car2",
],
"speed": [
1,
2,
],
}
Could someone help me? Thanks.
If name and type can have same value and car and speed various,then below is a reference for you
Note: in order to get an expected answer(solution),you need to make you question more clear,the most important thing is the value of which properties various
const data = [
{
"name": "name1",
"type": "type1",
"car": "car1",
"speed": 1
},
{
"name": "name1",
"type": "type1",
"car": "car2",
"speed": 2
},
]
const result = data.reduce((a,v) =>{
let obj = a.find(i => i.name == v.name)
if(obj){
obj.car.push(v.car)
obj.speed.push(v.speed)
}else{
a.push({'name':v.name,'type':v.type,'car':[v.car],'speed':[v.speed]})
}
return a
},[])
console.log(result)

how i get title from following response [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How i can get title or body from the following json response?
{
"message": "All Books",
"data": {
"current_page": 1,
"data": [
{
"id": 2,
"title": "The Quran",
"slug": "the-quran",
"body": "The Holy Quran",
"book": "/storage/books/1602685137.pdf",
"cover": "/storage/covers/1602685137.jpg",
"os": "both",
"price_ios": 0,
"price_android": 0,
"created_at": "2020-10-14T14:18:57.000000Z",
"updated_at": "2020-10-14T14:18:57.000000Z"
}
],
"first_page_url": "https://book.test/api/v1/books?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "https://book.test/api/v1/books?page=1",
"links": [
{
"url": null,
"label": "Previous",
"active": false
},
{
"url": "https://book.test/api/v1/books?page=1",
"label": 1,
"active": true
},
{
"url": null,
"label": "Next",
"active": false
}
],
"next_page_url": null,
"path": "https://book.test/api/v1/books",
"per_page": 15,
"prev_page_url": null,
"to": 1,
"total": 1
}
}
Say the json is stored in a variable res.
Since the second data object is stored as an array [].
title = res['data']['data'][0]['title'];
body = res['data']['data'][0]['body'];
If you find a case where the array has more than one object, then you will have to change 0 to the index of the object in the array.
Reference: www.json.org
Assuming your JSON is assigned to a variable called response you can access the body with:
let body = response.data.data[0].body
And the title with
let title = response.data.data[0].title
In case you want to loop over the data array in order to get a value for all entries (e.g. title), try this:
let titles = response.data.data.forEach(entry => console.log(entry.title));

Merging multiple JSON objects from an array together [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array of JSON objects and I want to merge the objects that have the same text together while finding the average of relevance and the sum of count across all of the same instances.
var keywords = [
{
"text": "service businesses",
"relevance": 0.626303,
"count": 1
},
{
"text": "service businesses",
"relevance": 0.87319,
"count": 5
},
{
"text": "service businesses",
"relevance": 0.05,
"count": 100
},
{
"text": "restaurants",
"relevance": 0.614567,
"count": 16
},
{
"text": "restaurants",
"relevance": 0.609875,
"count": 4
},
{
"text": "hotels",
"relevance": 0.594905,
"count": 1
},
I tried the solution posted here but, I am getting an output like this:
{
text: 'service businesses',
count: '[object Object][object Object]'
}
The output I am hoping for would look like this:
{
"text": "service businesses",
"relevance": 0.516497667,
"count": 106
},
{
"text": "restaurants",
"relevance": 0.612221,
"count": 20
},
{
"text": "hotels",
"relevance": 0.594905,
"count": 1
},
Any help is much appreciated!
Using Array.prototype.reduce, you can group the elements by the text and based on that group data, can get the output as follows.
var keywords = [{
"text": "service businesses",
"relevance": 0.626303,
"count": 1
},
{
"text": "service businesses",
"relevance": 0.87319,
"count": 5
},
{
"text": "service businesses",
"relevance": 0.05,
"count": 100
},
{
"text": "restaurants",
"relevance": 0.614567,
"count": 16
},
{
"text": "restaurants",
"relevance": 0.609875,
"count": 4
},
{
"text": "hotels",
"relevance": 0.594905,
"count": 1
}
];
const groupBy = keywords.reduce((acc, cur) => {
acc[cur.text] ? acc[cur.text] = {
...acc[cur.text],
count: acc[cur.text].count + cur.count,
relevance: [...acc[cur.text].relevance, cur.relevance]
} : acc[cur.text] = {
...cur,
relevance: [cur.relevance]
};
return acc;
}, {});
const output = Object.values(groupBy).map((item) => ({
...item,
relevance: item.relevance.reduce((acc, cur) => acc + cur, 0) / item.relevance.length
}));
console.log(output);
I ran it in two for loops and then calculated the relevance on the second loop.
I just kept track of the values in a normal object.
var keywords = [
{
"text": "service businesses",
"relevance": 0.626303,
"count": 1
},
{
"text": "service businesses",
"relevance": 0.87319,
"count": 5
},
{
"text": "service businesses",
"relevance": 0.05,
"count": 100
},
{
"text": "restaurants",
"relevance": 0.614567,
"count": 16
},
{
"text": "restaurants",
"relevance": 0.609875,
"count": 4
},
{
"text": "hotels",
"relevance": 0.594905,
"count": 1
}
]
const objectMerge = (arr) => {
let map = {};
for(let idx in arr){
const { text, relevance, count } = arr[idx];
if(!map[text]){
map[text] = {
count: 0,
relevance: []
}
}
map[text].count += count
map[text].relevance.push(relevance)
}
for(const key in map){
let lenOfRelevance = map[key].relevance.length
map[key].relevance = map[key].relevance.reduce((a,b) => a+b) / lenOfRelevance
}
return map
}
console.log(objectMerge(keywords))

Convert Enum Number To String [duplicate]

This question already has answers here:
How to get names of enum entries?
(43 answers)
Closed 4 years ago.
I have an enum file where I have defined an object for PaymentTypes:
export enum PaymentTypes {
Invoice = 1,
CreditCard = 2,
PrePayment = 3,
}
Now, when I receive data as an array from my database I also receive the PaymentType as a number:
order:
[
{ "id": 0, "name": "Available", "PaymentType": 1 },
{ "id": 1, "name": "Ready", "PaymentType": 3 },
{ "id": 2, "name": "Started", "PaymentType": 2 }
];
Now my question is, how can I filter out each payment type in the array and convert the number to the string that's defined in the enum file so that I can us this data to display it to the user in the front end?
So that I have something like this that I can work with:
orderFiltered:
[
{ "id": 0, "name": "Available", "PaymentType": "Invoice" },
{ "id": 1, "name": "Ready", "PaymentType": "PrePayment" },
{ "id": 2, "name": "Started", "PaymentType": "CreditCard" }
];
You can use map to create a new array of objects that contains the original data and the name of the enum member, which you can get using PaymentTypes[PaymentType]
let order = [
{ "id": 0, "name": "Available", "PaymentType": 1 },
{ "id": 1, "name": "Ready", "PaymentType": 3 },
{ "id": 2, "name": "Started", "PaymentType": 2 }
];
enum PaymentTypes {
Invoice = 1,
CreditCard = 2,
PrePayment = 3,
}
let orderFiltered = order.map(o => Object.assign({}, o, { PaymentTypeDisplayName: PaymentTypes[o.PaymentType] }));
console.log(orderFiltered);
One thing to note though is that using the enum member name as a display might not be the friendliest of use experiences.

Get value from JSON data [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this JSON data with me and I want to get the value of slug from every child.
The main problem is I don't know how much children will be generated after every time I got new data. In short generation of a child inside the child is dynamic that is not fixed.
So, How can I get the value of slug from every child that is present in JSON data?
Here I write one JSON data:
[
{
"id": 11,
"title": "Bottle",
"__domenu_params": {},
"href": "www.products.com",
"target": "_blank",
"slug": "/undefined"
},
{
"id": 10,
"title": "Pencils",
"__domenu_params": {},
"slug": "/Pencils"
},
{
"id": 9,
"title": "Stationary",
"__domenu_params": {},
"slug": "/Stationary"
},
{
"id": 8,
"title": "Pen",
"__domenu_params": {},
"slug": "/Pen"
},
{
"id": 7,
"title": "Cable",
"__domenu_params": {},
"slug": "/Cable"
},
{
"id": 5,
"title": "Electronics",
"__domenu_params": {},
"slug": "/Electronics",
"children": [
{
"id": 4,
"title": "Charger",
"__domenu_params": {},
"slug": "/Charger"
},
{
"id": 3,
"title": "Laptop",
"__domenu_params": {},
"slug": "/Laptop"
},
{
"id": 2,
"title": "Mobile",
"__domenu_params": {},
"slug": "/Mobile",
"href": "www.electronics.com",
"target": "_blank",
"children": [
{
"id": 6,
"title": "Pendrive",
"__domenu_params": {},
"slug": "/Pendrive",
"href": "www.pendrive.com",
"target": "_self"
}
]
}
]
}
]
I tried this code and get the value of slug from this JSON only. What should I do to get for every possible JSON data?
let data = [{"id":11,"title":"Bottle","__domenu_params":{},"href":"www.products.com","target":"_blank","slug":"/undefined"},{"id":10,"title":"Pencils","__domenu_params":{},"slug":"/Pencils"},{"id":9,"title":"Stationary","__domenu_params":{},"slug":"/Stationary"},{"id":8,"title":"Pen","__domenu_params":{},"slug":"/Pen"},{"id":7,"title":"Cable","__domenu_params":{},"slug":"/Cable"},{"id":5,"title":"Electronics","__domenu_params":{},"slug":"/Electronics","children":[{"id":4,"title":"Charger","__domenu_params":{},"slug":"/Charger"},{"id":3,"title":"Laptop","__domenu_params":{},"slug":"/Laptop"},{"id":2,"title":"Mobile","__domenu_params":{},"slug":"/Mobile","href":"www.electronics.com","target":"_blank","children":[{"id":6,"title":"Pendrive","__domenu_params":{},"slug":"/Pendrive","href":"www.pendrive.com","target":"_self"}]}]}]
for (let i = 0; i< data.length ; i++) {
// console.log(data[i]["children"])
if (data[i]["children"]) {
console.log("inside")
for (let j = 0; j < data[i]["children"].length; j++) {
// console.log(data[i]["children"][j])
if (data[i]["children"][j]["children"]) {
console.log(data[i]["children"][j]["children"])
}
}
}
}
You can use Recursion to parse this data easily:
let data = [{"id":11,"title":"Bottle","__domenu_params":{},"href":"www.products.com","target":"_blank","slug":"/undefined"},{"id":10,"title":"Pencils","__domenu_params":{},"slug":"/Pencils"},{"id":9,"title":"Stationary","__domenu_params":{},"slug":"/Stationary"},{"id":8,"title":"Pen","__domenu_params":{},"slug":"/Pen"},{"id":7,"title":"Cable","__domenu_params":{},"slug":"/Cable"},{"id":5,"title":"Electronics","__domenu_params":{},"slug":"/Electronics","children":[{"id":4,"title":"Charger","__domenu_params":{},"slug":"/Charger"},{"id":3,"title":"Laptop","__domenu_params":{},"slug":"/Laptop"},{"id":2,"title":"Mobile","__domenu_params":{},"slug":"/Mobile","href":"www.electronics.com","target":"_blank","children":[{"id":6,"title":"Pendrive","__domenu_params":{},"slug":"/Pendrive","href":"www.pendrive.com","target":"_self"}]}]}]
function getAllSlugs(categories) {
// For each category...
return categories.reduce((slugList, category) => {
// add the slug for the particular category...
slugList.push(category.slug);
// and, check if the category has children...
if (category.children && category.children.length) {
// if children are there, call the same function with the
// children and add the slugs of children
slugList = slugList.concat(getAllSlugs(category.children));
}
return slugList;
}, []);
}
// Call the function
getAllSlugs(data);
Output:
[ '/undefined',
'/Pencils',
'/Stationary',
'/Pen',
'/Cable',
'/Electronics',
'/Charger',
'/Laptop',
'/Mobile',
'/Pendrive' ]
Hope this helps!

Categories

Resources