How to add value to object and remove current value? - javascript

I have data like this :
users = [{
"emp_id": 1,
"user": {
"emp_full_name": "Test",
"emp_email": "test#gmail.com",
"emp_phone_no": null,
"preferred_work_type": null
},
"hashtag": {
"id": 1,
"name": "NodeJs",
"hashtag_group_id": 1
},
"difficulty": "HARD"
}, {
"emp_id": 2,
"user": {
"emp_full_name": "test2",
"emp_email": "test2#gmail.com",
"emp_phone_no": null,
"preferred_work_type": null
},
"hashtag": {
"id": 1,
"name": "NodeJs",
"hashtag_group_id": 1
},
"difficulty": "EASY"
}, {
"emp_id": 1,
"user": {
"emp_full_name": "Test",
"emp_email": "test#gmail.com",
"emp_phone_no": null,
"preferred_work_type": null
},
"hashtag": {
"id": 4,
"name": "Javascript",
"hashtag_group_id": 1
},
"difficulty": "HARD"
}]
I want to add hashtag to same the object that has the same emp_id. If emp_id has more than one data then the data that has the emp_id with the single hashtag data should be removed.
So basically this is what I expected:
[{
"emp_id": 1,
"user": {
"emp_full_name": "Test",
"emp_email": "test#gmail.com",
"emp_phone_no": null,
"preferred_work_type": null
},
"hashtag": [{
"id": 1,
"name": "NodeJs",
"hashtag_group_id": 1
}, {
"id": 4,
"name": "Javascript",
"hashtag_group_id": 1
}],
"difficulty": "HARD"
}, {
"emp_id": 2,
"user": {
"emp_full_name": "test2",
"emp_email": "test2#gmail.com",
"emp_phone_no": null,
"preferred_work_type": null
},
"hashtag": {
"id": 1,
"name": "NodeJs",
"hashtag_group_id": 1
},
"difficulty": "EASY"
}]
How to transform the data like that?
I have no idea how to solve that, I tried using filter(), and map() with some validation condition, but couldn't get it to work.

You can use .reduce() with .findIndex(). Try this
let users = '[{"emp_id": 1, "user": {"emp_full_name": "Test", "emp_email": "test#gmail.com", "emp_phone_no": null, "preferred_work_type": null }, "hashtag": {"id": 1, "name": "NodeJs", "hashtag_group_id": 1 }, "difficulty": "HARD"}, {"emp_id": 2, "user": {"emp_full_name": "test2", "emp_email": "test2#gmail.com", "emp_phone_no": null, "preferred_work_type": null }, "hashtag": {"id": 1, "name": "NodeJs", "hashtag_group_id": 1 }, "difficulty": "EASY"}, {"emp_id": 1, "user": {"emp_full_name": "Test", "emp_email": "test#gmail.com", "emp_phone_no": null, "preferred_work_type": null }, "hashtag": {"id": 4, "name": "Javascript", "hashtag_group_id": 1 }, "difficulty": "HARD"} ]';
users = JSON.parse(users)
users = users.reduce((arr, o) => {
let idx = arr.findIndex(({emp_id}) => emp_id === o.emp_id);
if( idx !== -1 ) arr[idx].hashtag = [].concat(arr[idx].hashtag, o.hashtag)
else arr.push(o)
return arr;
}, []);
console.log(users)

You could create a Map keyed by emp_id and collect the users by that key. When there is already an entry, extend the hashtag using [].concat. This will create an array if it wasn't an array yet.
const users = [{"emp_id": 1,"user": {"emp_full_name": "Test","emp_email": "test#gmail.com","emp_phone_no": null,"preferred_work_type": null},"hashtag": {"id": 1,"name": "NodeJs","hashtag_group_id": 1},"difficulty": "HARD"},{"emp_id": 2,"user": {"emp_full_name": "test2","emp_email": "test2#gmail.com","emp_phone_no": null,"preferred_work_type": null},"hashtag": {"id": 1,"name": "NodeJs","hashtag_group_id": 1},"difficulty": "EASY"},{"emp_id": 1,"user": {"emp_full_name": "Test","emp_email": "test#gmail.com","emp_phone_no": null,"preferred_work_type": null},"hashtag": {"id": 4,"name": "Javascript","hashtag_group_id": 1},"difficulty": "HARD"}];
const map = new Map;
for (const user of users) {
const match = map.get(user.emp_id);
if (match) match.hashtag = [].concat(match.hashtag, user.hashtag);
else map.set(user.emp_id, {...user});
}
const result = [...map.values()];
console.log(result);

Related

How can i make json file like this when i input

How can i make the cart_items like my expetation.. just it no more.. my problem just it :D
i just wanna make my cart_items like this.. hope you are can help me thanks. did I make the wrong method? and one more thing, i wanna make the qty inside the cart_items
this is my expectation
"cart": [
{
"id": 1,
"date": "12/10/2020",
"store": {
"id": 1,
"name": "Dirumah Aja",
"promo": 1
},
"cart_items": [
{
"id": 1,
"product": {
"id": 1,
"name": "Bakso Urat",
"price": 10000,
"promo": {
"nama": "promo"
}
},
"qty": 5
}
]
}
]
and this is what I got
"cart": [
{
"cart_items": {
"name": "Steak Sapi Impor",
"price": "38000",
"stock": "4",
"image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/steak.jpg?alt=media&token=46e0d769-96d3-440f-8edb-5fce2481ace0",
"promo": 3,
"id": 8,
"qty": 1
},
"store": {
"name": "Amanda Foods Store",
"email": "amanda#food.com",
"store_image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/full_hd_retina.jpeg?alt=media&token=3e602e86-661b-48ee-9e9c-af9f94a170d1",
"product": [
5,
7,
8,
2
],
"store_promo": 1,
"location": {
"street_name": "Jl. Kebon Gedang II B",
"province": "Jawa Barat",
"city": "Bandung",
"post_code": "40285"
},
"id": 1
},
"date_order": "Nov 03 2020 08:48:03",
"id": 2
}
]
This is my data
data() {
return {
promo_id: [],
promo_partner: [],
products: {},
qty: 1,
cart_items: [
{}
]
};
and this is my method
addToCart() {
const date = (new Date()).toString().split(' ').splice(1,4).join(' ')
this.products.cart_items = this.product;
this.products.cart_items.qty = this.qty;
this.products.store = this.partner;
this.products.date_order = date;
console.log(this.cart_items)
axios
.post("http://localhost:3000/cart/", this.products)
.then(() => {
swal("Belanja Berhasil!", {
icon: "success",
});
})
.catch((error) => console.log(error));
}
}
You need to use .push() to add items to an array. You're replacing the array with this.product.
if (!this.products.cart_items) { // initialize cart_items if necessary
this.products.cart_items = [];
}
this.products.cart_items.push({id: this.product.id, product: this.product, qty: this.qty});

JS Reduce with parent parameter

I am trying to solve my last issue with my reduce function to turn a nested JSON object into a flat list to enable easier searching.
Taking the JSON Below
{
"MovementPatterns": [
{
"Id": "",
"Name": "Warm-up",
"Exercises": [
{
"Id": "",
"Name": "Lizard Stretch",
"Level": 1,
"EquipmentRequired": ""
},
{
"Id": "",
"Name": "Pigeon Stretch",
"Level": 1,
"EquipmentRequired": ""
},
{
"Id": "",
"Name": "Core Hold",
"Level": 1,
"EquipmentRequired": ""
},
{
"Id": "",
"Name": "Superman",
"Level": 1,
"EquipmentRequired": ""
}
]
},
{
"Name": "Horizontal Push",
"Id": "",
"Exercises": [
{
"Id": "",
"Name": "Wall Push-up",
"Level": 0,
"VideoUrl": "",
"EquipmentRequired": ""
},
{
"Id": "",
"Name": "Push-up",
"Level": 1,
"EquipmentRequired": ""
},
{
"Id": "",
"Name": "Tap Push-up",
"Level": 2,
"EquipmentRequired": ""
},
{
"Id": "",
"Name": "Explosive Push-up",
"Level": 3,
"EquipmentRequired": ""
}
]
}
]
}
I have used the following code:
const exercises = data.MovementPatterns.reduce(
(a, {Exercises}) => [...a, ...Exercises, ...a],
[],
);
To flattern all the exercises from each movement pattern into a pure list of exercises...This is great, but I now need to INCLUDE in that JSON for each exercise the PARENT Movement Pattern ID e.g.
[
{
"Id": "",
"Name": "Lizard Stretch",
"Level": 1,
"MovementPatternId": 1,
"EquipmentRequired": ""
},
....
{
"Id": "",
"Name": "Wall Push-up",
"Level": 1,
"MovementPatternId": 2,
"EquipmentRequired": ""
},
]
Can someone please help me figure out how to do this with my reduce function :)
Thanks
You're almost close. Just append parent's Id as MovementPatternId to the each element of Exercises.
const exercises = ab.MovementPatterns.reduce(
(a, { Exercises, Id }) => [
...a,
...Exercises.map(e => ({ ...e, MovementPatternId: Id }))
],
[]
);

Need help in lodash combinations to get the below object

Below is my object First step is to check the socialAuth array of objects and get the platformName which has the showStats value as false.
I have accomplished the step1 as below
var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {'showStats': false}), "platformName");
['Twitter'] is the output of the arrList2
var creatorObj =
{
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [
{
"reach": 205976,
"_id": "asdfasdfasdf",
"profileUrl": null,
"engagements": 126,
"platformName": "Twitter"
}
],
"socialAuth": [
{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
},
{
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}
]
};
Second step is to check the above arrList2 with the sociaStats array and remove the value from it and print the object again.
I need help in this second step.
I need the resulting object as
var creatorObj =
{
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [],
"socialAuth": [
{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
},
{
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}
]
};
You need to use _.remove() to remove the elements from array based on your condition.
Demo
var creatorObj = {
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [{
"reach": 205976,
"_id": "asdfasdfasdf",
"profileUrl": null,
"engagements": 126,
"platformName": "Twitter"
}],
"socialAuth": [{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
}, {
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}]
};
var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {
'showStats': false
}), "platformName");
creatorObj.socialStats = _.remove(creatorObj.socialStats, function(n) {
return !_.includes(arrList2, n.platformName);
});
console.log(creatorObj);
document.write(JSON.stringify(creatorObj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Adding object properties from one JSON data file to another

I have two local JSON files. I want to add the property of one object from one file to the corresponding object in the other file.
Here is an example..
Array1:
[
{
"id": 1,
"username": "Joe Smith",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 2,
"username": "Jane Smith",
"pic": "images/profile/Jane_smith.jpg"
}
]
Array2:
[
{
"id": 3,
"userId": 1,
"profession": "dentist"
},
{
"id": 4,
"userId": 2,
"profession": "pilot"
}
The idea is to add the "pic" property from Array1 to the correct object in Array2. If the id from Array1 matches the userId from Array2, it's a correct match. Array2 would end up looking like this:
[
{
"id": 3,
"userId": 1,
"profession": "dentist",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 4,
"userId": 2,
"profession": "pilot",
"pic": "images/profile/Jane_smith.jpg"
}
Afterwards I'm going to use angular to display a name with the face. Hope I explained that ok. Any help would be much appreciated!
Just for the fun of it. In this example using https://lodash.com.
var people = [
{ "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" },
{ "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
{ "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];
var professions = [
{ "id": 3, "userId": 1, "profession": "dentist" },
{ "id": 4, "userId": 2, "profession": "pilot" }
];
var workers = _.map(people, function(human) {
var work = _.findWhere(professions, { 'userId': human.id });
return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});
console.log(workers);

Getting a variable from a multidimentional JSON array using Jquery

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Categories

Resources