Convert objects present in an object to NULL value - javascript

I have the following object names $scope.parameters. When i execute console.log as shown below, i get this result
console.log($scope.parameters);
Result
Object { Name: "Diana", id: 234, Size: Object, Location: Object, Details: "none" }
Name: "Diana"
id: 234,
Size: Object
Location: Object
Details: "none"
As the result shows the elements Size and Location as Object, i want it to be replaced with null. Also, i want it to be dynamic. for e.g. if any of the above elements are Object, it should replace it to null automatically.
Can someone please let me know how to achieve this.

Test out each key of the object with its type if object make them null
if (Object.getPrototypeOf($scope.parameters.Size) === Object.prototype) {
// True if its object change it to null
$scope.parameters.Size = null;
} else {
// do nothing
}
Make a function which takes parameters to test it out and return.

angular.forEach($scope.parameters, function(value, key) {
if(typeof value === "object"){
console.log(key);
$scope.parameters[key] = null;
}
});

Related

How to check if a value exists in array with .includes?

I know we can use .includes but I've been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.
The value is a string. That value comes from an object that has .name as a property within the object.
0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}
I mapped through the data and assigned each button with a value of {d.name}
I am using a button to get the value with this function below
and adding the values to 'favs'.
const favs = [];
function checkId(e) {
if (e.target.value !== "")
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
}
console.log
favs
[
"3-Bit-CNC-Starter-Pack",
"3-Bit-CNC-Starter-Pack"
]
How can I check to see if the value already exists within the array using .includes?
Just check before push:
function checkId(e) {
if (e.target.value !== ""
&& !favs.includes(e.target.value))
{
favs.push(e.target.value);
// other code here
}
}
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
if not false

Key exist in object in object

I need to check key exist in object of object. I have array of object and in every object i have one other object. I need to check the key is existing in object of object
var myarr = [{
hello: "world",
payload: {
kekek: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
},
{
hello: "world",
payload: {
qwe: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
}, {
hello: "world",
payload: {
qwe: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
},
{
hello: "world",
payload: {
asdf: 'sdfsdfsdf',
baby: 'sdfsdfsdfds'
}
}
]
let pp = myarr.payload.hasOwnProperty('eekey')
console.log(pp).
I need to check kekek in payload.
If I understood correctly, you want to check if every of object of your array contains a specific key in payload property. If so, you can use in operator to check if a property is present in a object. You can improve this snippet by checking if value is defined.
let key = 'kekek';
const everyObjectHasKey = myarr.every(item => item.payload && key in item.payload);
console.log(everyObjectHasKey);
In this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every , you can see more about every method for arrays

How to dynamically test for typeof array within object?

I have an user object - I want to generate test for each user property and check if it's the right type. However as typeof array is an object assertion fails on array properties with "AssertionError: expected [ 1 ] to be an object".
I have therefore checked if the property is an array and then generate special test for it. I'm wondering if this is the right approach? I have a feeling I'm misssing something obvious.
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
it(`should have property ${property}, type: array`, function () {
user.should.have.property(property);
});
} else {
it(`should have property ${property}, type: ${(typeof pureUser[property])}`, function () {
user.should.have.property(property);
user[property].should.be.a(typeof pureUser[property]);
});
}
});
pureUser is something like this:
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
User variable is defined elsewhere via got.js
change your test to be pureUser[property].should.be.an.Array or user[property].should.be.an.Array
forEach
The forEach() method calls a provided function once for each element in an array, in order.
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
console.log('Yes, it\'s an Array')
//it(`should have property ${property}, type: array`, function () {
// user.should.have.property(property);
//});
} else {
console.log('No, it\'s not an Array')
//it(`should have property ${property}, type: ${(typeof property)}`, function () {
//user.should.have.property(property);
// user[property].should.be.a(typeof pureUser[property]);
//});
}
});
When you use forEach on pureUser, the parameter will be the objects properties, like username, id, etc
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
Object.keys(pureUser).forEach(property =>{
console.log(property);
});
You can also access the array in your forEach function.
arr.forEach(item, index, arr)

JS Remove multi-dimensional data property using array of properties

Basically I have got an object, which will be multi-dimensional and the properties could be named anything and it could have many dimensions.
At some point I will need to append/splice a property within this object, from code which won't know it's position.
So, an example object:
let obj = {
response: {
locations: {
data: [
0: Object,
1: Object,
2: Object,
]
}
},
endpoint: null
}
I need to splice out data.locations.data[1], the only information I have is the below array and the index. Obviously I will know the first property will be response.
['locations','data']
index: 1
Edit:
My mistake, the data property has an array value not an object!
You can use Array#reduce() and pass in obj.response as the start value to get at the nested parent which based on the array shown would be obj.response.locations.data.
Then splice() the indexed item in that parent or do whatever other modifications are needed
const arr = ['locations','data'],
index= 1,
obj = {
response: {
locations: {
data: [{id:1},{id:2}, {id:3}]
}
},
endpoint: null
}
const targetArr = arr.reduce((a,c)=> (a[c]), obj.response);
targetArr.splice(index,1);
console.log(obj)

Elegant way to remove every instance of a key in an object?

I have an object and I want to copy this object and remove every instance of description from it. What is an elegant way of doing this?
here's how the object looks:
{
properties: {
a: {
value: foo,
description: bar
},
b: {
value: foo,
description: bar
}
}
Use the second argument to JSON.parse:
const output = JSON.parse(
JSON.stringify(input),
(key, value) => key === "description" ? undefined : value
);
A return value of undefined from this function tells JSON.parse to skip it.

Categories