How to extend an object while ignoring null values? - javascript

Say for example I have an object of
var user = {
"Name": "Dan",
"Age": 27,
"Hobbies": null
};
which I would like to merge onto the following base object so that my user object will have all the required properties
var base = {
"Name": null,
"Height": null,
"Age": null,
"Hobbies": [
{ "Name": "Tennis", "Location": null },
{ "Name": "Football", "Location": null },
{ "Name": "Rugby", "Location": null }
]
};
The easiest way to merge to the two objects would be to extend the base object with the user object as follows
$.extend(true, base, user);
which would modify the base object to be
{
"Name": "Dan",
"Height": null,
"Age": 27,
"Hobbies": null
};
My question would be how can I get the extend method to not override null values? For example, in this instance, how can I still obtain a list of hobbies if the users hobby list is null so I end up with the following
{
"Name": "Dan",
"Height": null,
"Age": 27,
"Hobbies": [
{ "Name": "Tennis", "Location": null },
{ "Name": "Football", "Location": null },
{ "Name": "Rugby", "Location": null }
]
};

You may use undefined as value which will be ignored by jQuery.extend.
var user = { "Name": "Dan",
"Age:" 27,
"Hobbies": undefined
};
$.extend(true, base, user);

Related

Object has many arrays, loop through each and change some value

I have an object that has a whole host of arrays and properties. There is a property called targetProperty which appears in various places of the object.
I have a function where if the user clicks yes, every instance of that property needs to be reassigned to a new value.
The problem is the function that I used for assigning a new value doesn't work in this senario:
reassingPropertyInObj(obj, status) {
if (typeof obj === 'object' && obj !== null) {
obj.targetProperty = status;
for (const key in obj) {
this.handleExpandCollapseClick(obj[key], status);
}
}
},
Does anyone have a solution for this? Also can't use JSON.parse() or anything like that because the properties need to stay reactive for later reassignment if needed by the user.
Below is an example of one object:
{
"id": 16,
"ref_study_id": "3412333",
"title": "SomePersonNameOne",
"capabilities_available": [
{
"id": 75,
"name": "Clinical Data",
},
{
"id": 538,
"name": "RK's Capability",
}
],
"capabilities_impacted": [],
"businessImpact": {
"id": 2,
"name": "Medium"
},
"sites_impacted": [],
"sites_available": []
},
{
"id": 6,
"ref_study_id": "123124",
"title": null,
"capabilities_available": [
{
"id": 37,
"name": "Clinical Site Experience,
},
{
"id": 41,
"name": "Experience",
}
],
"capabilities_impacted": [
{
"id": 37,
"name": "Information Exchange",
"is_study_level": false,
"businessImpact": {
"id": 2,
"name": "Medium"
}
},
{
"id": 39,
"name": "IT/Data Experience",
"is_study_level": false,
"businessImpact": {
"id": 2,
"name": "Medium"
}
},
{
"id": 34,
"name": "Mgmt & Storage",
"is_study_level": false,
"businessImpact": {
"id": 3,
"name": "Minor"
}
}
],
"businessImpact": {
"id": 2,
"name": "Medium"
},
"sites_impacted": [],
"sites_available": []
},
And the property in question is businessImpact. As you can see it appears by itself as a property and inside array (and sometimes those arrays of arrays of their own).
I setup a function like:
arrayOfProperties.forEach((property) => {
obj[property].forEach((o) => {
o.businessImpact = newVal;
});
});
But of course it doesn't go deep enough.

How can I delete a particular column ( key value) in the table (json) with Javascript and Typescript

[{
"name": "employeeOne",
"age": 22,
"position": "UI",
"city": "Chennai"
},
{
"name": "employeeTwo",
"age": 23,
"position": "UI",
"city": "Bangalore"
}
]
If I delete "Position"
key & value from the json the result should be like[
[{
"name": "employeeOne",
"age": 22,
"city": "Chennai"
}, {
"name": "employeeTwo",
"age": 23,
"city": "Bangalore"
}]
If we have list of employee in a table I want to delete all the employees position column only. How can I achieve this with JavaScript and Typescript
I tried
const output = delete employee.position
but getting an error.
var data = [{
"name": "employeeOne",
"age": 22,
"position": "UI",
"city": "Chennai"
},
{
"name": "employeeTwo",
"age": 23,
"position": "UI",
"city": "Bangalore"
}
];
data.forEach( item => {delete item.position;});
console.log(data);
You have an array of objects there. You would have to loop through the array, deleting the property in each object individually.
take a look at the delete operation
pseudo:
foreach obj in jsonArray
{
delete obj["position"];
}
also works:
obj[position]
obj.position
http://perfectionkills.com/understanding-delete/

Fetch the no of of occurence in a array based on other key value

var json = [{
"city": "California",
"name": "Joe",
"age": 17,
"type",:"custom"
}, {
"city": "California",
"name": "Bob",
"age": 17,
"type",:"predefined"
}, {
"city": "California",
"name": "Bob",
"age": 35,
"type",:"custom"
}, {
"city": "Texas",
"name": "Bob",
"age": 35,
"type",:"custom"
}, {
"city": "Florida",
"name": "Bob",
"age": 35,
"type",:"predefined"
}];
I have above array and i have to construct object, based on "type" value i.e "predefined" or "custom" as below
updatedjson = {
"predefined": [{
"name": "California",
"count": 1
}, {
"name": "Florida",
"count": 1
}]
"custom": [{
"name": "California",
"count": 2
}, {
"name": "Texas",
"count": 1
}]
}
Any Approach using javascript or lodash
Using Lodash
var json = [{
"city": "California",
"name": "Joe",
"age": 17,
"type": "custom"
}, {
"city": "California",
"name": "Bob",
"age": 17,
"type": "predefined"
}, {
"city": "California",
"name": "Bob",
"age": 35,
"type": "custom"
}, {
"city": "Texas",
"name": "Bob",
"age": 35,
"type": "custom"
}, {
"city": "Florida",
"name": "Bob",
"age": 35,
"type": "predefined"
}];
// Solution to the problem
var updatedJson = _(json).groupBy("type").value(); // #1
_.forOwn(updatedJson, function(value, key) {
let countByCity = _(value).countBy('city').value(); // #2
let res = [];
_.forOwn(countByCity, function(value, key) {
res.push({ // #3
name: key,
count: value
});
});
updatedJson[key] = res;
});
console.log(updatedJson);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
Explanation
Code first groups by type
Then counts by cities, within the group
Finally pushes the count object into an array, in the expected format
You can use reduce & findIndex
var json = [{
"city": "California",
"name": "Joe",
"age": 17,
"type": "custom"
}, {
"city": "California",
"name": "Bob",
"age": 17,
"type": "predefined"
}, {
"city": "California",
"name": "Bob",
"age": 35,
"type": "custom"
}, {
"city": "Texas",
"name": "Bob",
"age": 35,
"type": "custom"
}, {
"city": "Florida",
"name": "Bob",
"age": 35,
"type": "predefined"
}];
var updatedjson = json.reduce(function(result, item) {
// check if type is present in the object
// if not present then add a key by name custom/predefined
if (!result[item.type]) {
result[item.type] = [];
// add city name and intial count
result[item.type].push({
name: item.city,
count: 1
})
} else {
// now find the index of the object whe name matches with current city
let m = result[item.type].findIndex(function(obj) {
return obj.name === item.city
})
// if no matches then add the new object to either custom/predefined
if (m === -1) {
result[item.type].push({
name: item.city,
count: 1
})
} else {
// if matches then increase the value of count
result[item.type][m].count += 1
}
}
return result;
}, {});
console.log(updatedjson)
You can use array.reduce to create a new object with the aggregated data. Example:
const result = json.reduce((obj, data) => {
// if this is a new type, we must initialize it as an empty array and push the first record.
if(!obj[data.type]) {
obj[data.type] = [];
obj[data.type].push({name: data.city, count: 1});
return obj;
}
// else ... check if the current city is present in that type
const existingRecord = obj[data.type].find(d => d.name === data.city);
if(!existingRecord) {
// if the city is not present in that type, we initialize it with count 1
obj[data.type].push({name: data.city, count: 1});
return obj;
}
// if the city is present, we just update count = count + 1;
existingRecord.count++;
return obj;
}, { })
Now, you probably want to extract some of that logic into separate functions to increase readability. I don't think you need lodash for this but in the case you already have it included in your project then feel free to use it :P

Javascript array value undefined?

I am currently working on a REST API / website project, where my REST API has to return an array of objects from the server, via a response and using GSON to make a Json array out of the data. However, when trying to get values from the javascript array for the website, I keep getting undefined. This is the array:
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [
{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}
],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [
{
"id": 1,
"number": "123124",
"info": "0x1"
}
]
}
];
When I try to call userArr[0].firstName, I get an error saying that it's undefined, even though the data is there. This is from a get call, which I am doing in my javascript from my REST API, which sends back this specific array. I have tried looping through the array, with multiple objects inside, however I am unable to retrieve any info at all.
Your userArr is an array of objects which do not have firstName property. They have only one property named 0x1 for some reason. And this 0x1 property has firstName property.
You can access firstName of 0x1 property using this notation:
userArr[0]["0x1"].firstName
Here is the working demo:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0]["0x1"].firstName);
By the way, there is a missing closing } bracket in the end of the array in your code.
I think if you write this code this way it is easy to understand and find the problem
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{"id": 1,"name": "Fodbold","people": ["0x1"]}],
"id": 1,
"address": {"id": 1,"street": "Street1","cityInfo": {"id": 1,"zipCode": "0555","city": "Scanning"},
"infoList": ["0x1","0x2"]},
"phones": [{"id": 1,"number": "123124","info": "0x1"}]
}
}
];
You also missing the last second bracket.
Then you could use this console.log(userArr[0]["0x1"].firstName);
try this one
userArr[0]["0x1"].firstName
Incase value "0x1" is dynamic, you can access it by using Object.keys(userArr[0])[0] to get the first key of the object.
Here is solution:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0][Object.keys(userArr[0])[0]].firstName);

Converting object to array within an object in JavaScript

I am getting back data in a format that is not acceptable to the processing system and I am trying to convert the data. Below is the data I get and the required JSON below that. I tried different things like finding an Object within the data and checking if it has more than one element then converting that object to Array[] but I am unable to do so.
If you have any inputs, I would appreciate it.
if(typeof ob1=== "object" && Object.keys(ob1.length > 1) && typeof Object.keys(ob1) === "object" )
{
console.log(ob1); // I get all the objects and not the parent object i need to change.
}
Present data:
ob1 : {id: 1, details: Object, profession: "Business"}
JSON:
{
"id": "1",
"details": {
"0": {
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
"1": {
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
},
"profession": "Business"
}
Required data:
{id: 1, details: Array[2], profession: "Business"}
Required JSON:
{
"id": "1",
"details": [
{
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
{
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
],
"profession": "Business"
}
You have to go through the details object and convert it into an array:
var x = {
details: {
0: {a: 1},
1: {a: 2}
}
}
var detailsArr = [];
for(key in x.details) {
detailsArr.push(x.details[key]);
}
x.details = detailsArr;
//x.details = [{a: 1}, {a: 2}]

Categories