How to insert json values into object - javascript

I have a predefined object (SampleObject) like this:
{
ID: "",
Name: "",
URL: "",
prevName: "",
Code: "",
}
And I want to insert the below json object values(values only):
var object =
{
"Sample" : {
"Data" : {
"ID" : "12345",
"Name" : "SampleName: Name",
"URL" : "www.google.com",
"prevName" : "phones",
"Code" : "USD"
}
}
into the above predefined object. How do I do that?

You can just use a for in loop and set the value checking if the key is present in the object or not.
Check if the property is present on the emptyObject, and then copy that over to it.
for (var key in pageInfo) {
var value = pageInfo[key];
if (obj.hasOwnProperty(key)) {
obj[key] = value;
}
}
Code Pen

It is an object. There is no reason to use push or another method.
Simply take your defined object pageObject.page and assign a new key value pair with literal syntax.
pageObject.page['pageInfo'] = predefinedObject
or in more common syntax
pageObject.page.pageInfo = predefinedObject

Use the following code below the JSON Object
var digitalData= {page:{pageInfo:''}};
digitalData.page.pageInfo = pageObject.page.pageInfo;
console.log(digitalData.page.pageInfo);

Related

Having trouble reading data from an object

I don't understand how to read the genre data.
"data":
"genres": [
{
"id": 0,
"type": "string",
"name": "string",
"url": "string"
},
{
"id": 1,
"type": "string",
"name": "string",
"url": "string"
}
],
}
I want it to end up being displayed like
name1, name2, name3
and (if possible) I want to have each of the names have the link to their corresponding url.
I have tried to find that data by
var genres = data.genres;
But that just returns [object Object],[object Object]
Im guessing that you have to read the data from those objects, but I don't know how to.
What you need to understand from that is the following: "data" is an object and it has a "genres" property which has an array of objects inside it. Knowing this you can just do the following:
const name1 = data.genres[0].name; // Gets the first name
const name2 = data.genres[1].name; // Gets the second name
If you want to loop through the genre data, then you need to iterate through the objects inside the "genres" property:
data.genres.map((genre) => console.log(genre.name)); // Logs all names
This would be a more common example:
for (let i = 0; i < data.genres.length; i++) {
const name = data.genres[i].name;
console.log(name); // Logging the names
}
You'll have to loop to go through the data, and create a-elements to create a link. You'll also need a parent element to append the links to:
const yourParentElement = document.getElementById("parent");
var genres = data.genres;
genres.forEach(genre => {
var lnkGenre = document.createElement("a");
lnkGenre.textContent = genre.name;
lnkGenre.href = genre.url;
You can also add classes or an id here:
lnkGenre.classList.add("yourClass");
lnkGenre.id = genre.id;
yourParentElement.appendChild(lnkGenre);
});

Getting error: Cannot read properties of undefined in javascript

While calling function getting error:
Uncaught TypeError: Cannot read properties of undefined (reading 'username')
at getLoginData (<anonymous>:3:30)
at <anonymous>:1:1"
role1 has value "administrator", but why it is not able to call in datamodel? (Datamodel here refers is another JSON file)
datamodel = {
administrator: [
{
username: "abc#xyz.com",
password: "abc#1234",
},
{
username: "abcd#xyz.com",
password: "xyz#1234",
},
],
};
function getLoginData(role1) {
console.log(role1);
let name = datamodel.role1.username;
}
getLoginData("administrator[0]");
You can't access object in that was, the code thinks that role1 is a key in that Object.
function getLoginData(role1){
console.log(role1)
let name=datamodel[role1][0].username
}
getLoginData("administrator")
var datamodel = {
"administrator": [
{
"username": "abc#io.com",
"password": "abc#1234"
},
{
"username": "xyz#io.com",
"password": "xyz#1234"
}
]
}
console.log(datamodel);
var name = datamodel.administrator[0].username; //get the name of administrator[0] = "rinty.kurian#espacenetworks.io"
console.log(name);
Try this :)
First of all you need to use Brackets Notation to access an object's attribute that is stored inside of another variable. So assuming you want the first credentials from the administrators array you would write something like datamodel.administrator[0].
Since, as it seems from your function's call, getLoginData('administrator[0]'), you would like that the function getLoginData to take care of accessing the inner administrators array which we cannot directly using brackets notation as datamodel['administrators[0]'] will raise an error because the attribute "administrators[0]" (string) doesn't exist in the datamodel object.
What we need to do is to try to extract the index of the items we want to return, if it exists, and then use that to return the right credentials from the datamodel object.
To do so, we will split the argument that is passed to getLoginData to get the attribute we want to access (ex: administrators) and the index (ex: 0).
Here's a live demo to implement such functionality:
const dataModel = {
"administrator": [{
"username": "abc#xyz.com",
"password": "abc#1234"
},
{
"username": "abcd#xyz.com",
"password": "xyz#1234"
}
]
},
/**
* a function that accepts an attribute name and optional index to get from "datamodel" object
*/
getLoginData = role => {
/**
* split the role parameter to get the wanted index if there is one
* the trick here is that we will replace the brackets around the index with a space and only keep the index itself (we'll get rid of those brackets)
* we should make some checks to prevent undefined index like errors
*/
const splitted = role.replace(/\[(\d+)\]/, ' $1').split(' '),
attr = dataModel[splitted[0]] ? (splitted.length > 1 ? dataModel[splitted[0]][splitted[1]] : dataModel[splitted[0]]) : null;
/** return the appropriete attribute or null if not defined */
return attr ? attr.username : null;
};
// prints: "abc#xyz.com"
console.log(getLoginData("administrator[0]"))
UPDATE
Here's another possible solution that works by passing the item index as the second parameter to datamodel object.
const dataModel = {
"administrator": [{
"username": "abc#xyz.com",
"password": "abc#1234"
},
{
"username": "abcd#xyz.com",
"password": "xyz#1234"
}
]
},
/**
* a function that accepts an attribute name and an index to get from "datamodel" object
*/
getLoginData = (role, index) => dataModel[role] && dataModel[role][index] ? dataModel[role][index].username : null;
// prints: "abc#xyz.com"
console.log(getLoginData("administrator", 0))

how to filter json array using another json array?

I have an response as a json array with lots of records but i want to filter that json array by using another json array.
my json response
http://prntscr.com/lvxwob
and my filter json array be like
"filterParams" : [
{
"param" : "actualSum",
"value" : "95",
"type" : "text",
"comparision" : "isEqual"
},
{
"param" : "wbsSort",
"value" : "6",
"type" : "text",
"comparision" : "isEqual"
}
],
so how can i filter my response using javascript or node js anything. i want to get filtered data like match param with reponse param and its value.
e.g.
if there is match value of actualSum with 95 and wbsSort's value equal to 6 then it will return true other wise false.
You could filter the items in the result array where the item matches every parameter in filterParams. If you only want to check if at least one match exists replace .filter with .some
e.g.
var matches = results.filter(item =>
filterParams.every(paramItem =>
item[paramItem.param] === paramItem.value));
I've limited it to equals comparison but you can expand the comparison using a switch based on the other comparison types you have.
A way to do this without having to hardcode every check would be to create a compare function using the filterParams. So you would do something like this, where compareFunction creates a new function using filterParams to initialize the variables to check and returns whether the current item has these values. So for any further check you want to do, you will only have to add it to filterParams. Hope this helps.
const filterParams = [{
"param" : "actualSum",
"value" : "95",
"type" : "text",
"comparison" : "isEqual"
}, {
"param" : "wbsSort",
"value" : "6",
"type" : "text",
"comparison" : "isEqual"
}];
const data = [{ actualSum: 95, wbsSort: 6 }, { actualSum: 95, wbsSort: 10 }];
const operators = {
'isEqual': '==='
};
const compareFunction = (params) =>
(item) => new Function(
params.reduce((acc, { param, value }) => `${acc} const ${param} = ${value};`, '') +
params.reduce((acc, { param, value, comparison }, i) => `${acc} ${param} ${operators[comparison]} ${item[param]} ${i !== params.length - 1 ? '&&' : ';'}`, 'return ')
)();
const filteredData = data.filter(compareFunction(filterParams));
console.log(filteredData);

How can I remove null from JSON object with AngularJS?

I'm trying to remove an object from Json Object it works..but it replace it with null..i dont know why, how can i remove the null value from the json..heres the function :
company.deleteExternalLinkFromGrid = function (row, matricule) {
// console.log('Inside of deleteModal, code = ' + code);
//$scope.sitting= {};
console.log(matricule);
//console.log(JSON.stringify(linkJsonObj));
delete linkJsonObj[matricule];
console.log(JSON.stringify(linkJsonObj));
};
heres the object:
[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null]
You can use filter(), x will be without null's.
function test()
{
var x =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null].filter(isNotNull);
alert(JSON.stringify(x));
}
function isNotNull(value) {
return value != null;
}
fiddle
There are multiple ways to delete an object from an array of objects in JavaScript. You don't need AngularJS for that, you can use VanillaJS.
If you just want the nulls filtered you can use
var yourArray =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null];
yourArray = yourArray.filter(function(elt){
return elt != null;
});
But this loses the original reference to your object.
If you want to keep the reference, Use array.splice().
yourArray.forEach(function(){
yourArray.splice(yourArray.indexOf(null),1);
});
now you will have null less array in yourArray. This actually deletes an object from an array without changing the reference,
delete will replaced the object with undefined
You can filter the array to remove them using Array#filter()
var array = [{
"name": "xxx",
"link": "www.ddd.com",
"id": 0,
"$$hashKey": "uiGid-001Z"
}, {
"name": "xx",
"link": "www.dddcom",
"id": 1,
"$$hashey": "uiGrid-0029"
}, {
"name": "xxx",
"link": "www.ddd.com",
"id": 2
}];
delete array[1];
array = array.filter(a=>a);
console.log(JSON.stringify(array));

Remove specified element from associated array

Hi I am looking for ways to delete the elements from associate array.
I need to remove values like null and '' while in the loop. But I cant because I know that I will need to identify and the build array to store, Then use elements in the new array to seek and remove them.
var storeData3 = [
{ 'key' : 'value1' },
{ 'key' : 'value2' },
{ 'key' : 'value3' },
{ 'key' : null },
{ 'key' : '' },
{ 'key' : 'value10'}
];
Try this:-
Using Array.filter to get the data after omitting unwanted data.
var result= storeData3
.filter(function(val){
return (val.key != '' && val.key != null)});
.filter()
Fiddle

Categories