adding objects to an already existing javascript object - javascript

I have a javascript object that contains addresses as follows
var addressList = [
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]
I want to add another "address" to it so i have somthing like the following
[
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"},
{"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]
i cant figure out how to do this ?

Use Array#push to add a new object to the array:
addressList.push({"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"});

It's not clear to me what you're encountering, but the probable problem you're running into is that the first snippet you give is a javascript Object, and the second snippet is an Array. You'd need to so something like:
var addressList = [];
addressList.push({"AddressID":"10011",...});
You could then iterate over the list using a forEach:
addressList.forEach(function(address) {
alert(address.AddressID);
doSomethingWithAddress(address);
});
You can read more about Arrays on the MDN

addressList.push({AddressID: 1234, Country: 'Foo', ...});

Related

How to push each object value into array from json?

I have a JSON response with key-values like:
....
"usp-custom-90":"45.45257926613316,9.178168599999935"
....
Note usp-custom-90has dash!
I need something like (fields doens't exist, it's just an example):
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Where coordsB is an array defined before.
The json would be:
],
"usp-custom-90":"45.47841306255037,9.120865849999973",
"_links":{
"self":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts\/128402"
}
],
"collection":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts"
}
],
"about":[
I need to push the value of each "usp-custom-90"
Full code (wrong as it is using fields which doesn't exist):
fetch('https://www.example.it/wp-json/wp/v2/posts?per_page=50&status=publish')
.then(res => res.json())
.then(data =>{
var coordsB = [];
console.log(data);
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Based on the data sample linked in the comments, the structure is an array of objects, each object containing a usp-custom-90 property. This is a perfect situation for the map operator for arrays.
So in the above code, this one line will do it all for you. It will create the array and populate it with all the values you're looking for.
var coordsB = data.map(x=> x["usp-custom-90"])
Something along these lines would do I guess.
Object.entries(object).reduce((ac,[k,v],i,a)=>(ac.push(v['usp-custom-90']),ac),[])
Looks like from your paste bin main object is an array with objects inside which have the key you want then:
YourMainArray.reduce((ac,d,i,a)=>(ac.push(d['usp-custom-90']),ac),[])
Tested it, gives you this:
["45.45257926613316,9.178168599999935", "45.47841306255037,9.120865849999973", "9.924,-84.090", "44.948,9.039", "45.464150416139695,9.1906395499999", "45.651,11.303", "43.83734441524854,7.905822499999999", "45.05926341591318,9.3354875", "44.872988115810074,13.85009094999998", "44.97805886586813,8.895478499999967", "45.472119466144186,9.173527250000006", "45.165,9.183", "41.937,12.441", "45.464993216140186,9.147909499999969", "45.48624411615216,9.16677489999995", "45.209,9.147", "45.464993216140186,9.147909499999969", "41.848264464222716,12.665936949999946", "45.464993216140186,9.147909499999969", "45.46851557705748,9.139416449999999", "44.507,11.314", "36.731,14.873", "36.222,-121.759", "10.093,77.060", "45.454327616134165,9.175796900000023", "45.469282816142574,9.176045000000045"]

Deleting or get rid of complete array which doesnt have all desired items in an array

delete array which doesnt have "category" field
req:wanted to get rid of obj[0] & obj[2] as they doesn't hav category field...
for example:
js data:
var obj=[
{"email":"rteh#tm.com","event":"open"},
{"ip":"24.38.43.233","email":"rtehrani#tmcnet.com","category":["webinar"]},
{"email":"glin#gl.com","event":"open"},
{"ip":"24.98.43.230","email":"glin#gl.com","category":["webinar"]},
{"ip":"24.77.55.931","email":"klen#gmail.com","category":["webinar"]},
{"ip":"44.67.85.456","email":"bryan#gmail.com","category":["webinar"]}
];
expected o/p:
var obj=[
{"ip":"24.38.43.233","email":"rtehrani#tmcnet.com","category":["webinar"]},
{"ip":"24.98.43.230","email":"glin#gl.com","category":["webinar"]},
{"ip":"24.77.55.931","email":"klen#gmail.com","category":["webinar"]},
{"ip":"44.67.85.456","email":"bryan#gmail.com","category":["webinar"]}
];
question is edited...for simple understanding,
thanks in advance....
I'm not sure I completely understand the question, but I'm assuming that you want to get rid of all objects that don't have a category property. This snippet would do it.
var obj=[
{"email":"rteh#tm.com","event":"open"},
{"ip":"24.38.43.233","email":"rtehrani#tmcnet.com","category":["webinar"]},
{"email":"glin#gl.com","event":"open"},
{"ip":"24.38.43.230","email":"glin#gl.com","category":["webinar"]}
];
var result = obj.filter(participation => participation.hasOwnProperty('category'));
console.log(result);

Get first item in a json list with Nodejs

I have a json data with this structure in Nodejs
{
ids:
[
'Deploy:1426ba8e-5d9d-4572-888d-2265ae7474ce',
'Deploy:f899e1e4-d512-469d-979c-835e98ced8b7',
'Deploy:02f530d3-9727-4894-a1be-c2f90c430251',
'Deploy:254f10bd-374a-41c8-a0ca-7a5ba37e7d2e',
'Deploy:511f878b-a9e9-4c6b-bbf8-1024131fcc86'
]
}
How can I get the first value for "Deploy" key? Preferably JS code not extra libraries.
So for example, I want to get this value 1426ba8e-5d9d-4572-888d-2265ae7474ce which is the first entry.
var firstDeployValue = data.ids[0].split(':')[1]; should give you 1426ba8e-5d9d-4572-888d-2265ae7474ce If you want Deploy in there as well remove the split bit.
You can achieve that with split;
const data = {
ids: [
'Deploy:1426ba8e-5d9d-4572-888d-2265ae7474ce',
'Deploy:f899e1e4-d512-469d-979c-835e98ced8b7',
'Deploy:02f530d3-9727-4894-a1be-c2f90c430251',
'Deploy:254f10bd-374a-41c8-a0ca-7a5ba37e7d2e',
'Deploy:511f878b-a9e9-4c6b-bbf8-1024131fcc86'
]
};
const result = data.ids[0].split(':')[1];
console.log(result);
you can just assign it to an object, like
jsonObj = {
ids:
[
'Deploy:1426ba8e-5d9d-4572-888d-2265ae7474ce',
'Deploy:f899e1e4-d512-469d-979c-835e98ced8b7',
'Deploy:02f530d3-9727-4894-a1be-c2f90c430251',
'Deploy:254f10bd-374a-41c8-a0ca-7a5ba37e7d2e',
'Deploy:511f878b-a9e9-4c6b-bbf8-1024131fcc86'
]
}
and then just access it using jsonObj.ids[0].match(regexpattern)

JavaScript: Access object variable inside nested array

How would I access ArrayObjectVariable inside
ArrayObject[0]? I know if you don't have a [ ] around it its as simple
as ArrayObject[0].ArrayObjectVariable?
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{ ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0]???);
I didn't realize the whole "ArrayObject[0][0].ArrayObjectVariable" thing. Thanks for the replies. I was trying it with just one ("[0]") instead of two ("[0][0]"). My second question is, what is the second "[0]" for? I just tried making multiple variables and it still used "[0][0]" ? So what's the second "[0]" controlling?
Third question? I noticed that it created a variable outside the array when I did that? When I change the value of the variable in the array, it has no effect on the one outside of it? Likewise, when I change the value of the variable outside of the array it has no effect on the one inside it. Is there a way to create the array without creating a variable outside of the array with the same name? Thanks :)
OK figured it out :) Just make the Object in the array without the "[ ]". The whole point of this was to figure out how to access nested items but I got it now. Didn't realize how to make them without the "[ ]". Example for those of you struggling like I was:
// create variables that we are going to use in Array Objects. Or make a function with the values.
var ATV1 = 'AyTeeVeeOne', ATV2 = 'AyTeeVeeTwo', ANV1 = 'AyEnVeeOne';
var ATV3 = 'AyTeeVeeThree', ATV4 = 'AyTeeVeeFour', ANV2 = 'AyEnVeeTwo';
// Make an Array
var ArrayObject;
ArrayObject = [{}];
// Insert variables into Array object(s).
ArrayObject[0] = {ArrayTestObject1 : { ArrayTestValue1:ATV1,
ArrayNestedObject1:{ ArrayNestedValue1:ANV1 },
ArrayTestValue2:ATV2
}};
ArrayObject[1] = {ArrayTestObject2 : { ArrayTestValue3:ATV3,
ArrayNestedObject2:{ ArrayNestedValue2:ANV2 },
ArrayTestValue4:ATV4
}};
// Access Array Object Variables
alert(ArrayObject[0].ArrayTestObject1.ArrayTestValue1) // Example 1
alert(ArrayObject[1].ArrayTestObject2.ArrayNestedObject2.ArrayNestedValue2) // Example 2
ArrayObject[0][0].ArrayObjectVariable
You have an array for the value of ArrayObject[0], so treat it like any other array.
use this:here you have ArrayObject as array and you are creating index as zero to the array and in that on zeroth place ArrayObjectVariable key resides.
<script>
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{
ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0][0].ArrayObjectVariable);
</script>

Accessing an associative array using jQuery

I have an associative array here -
var dataset = {
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
}
I tried accessing the 'userLabels' object using jQuery using various methods but I failed. I think I am doing something wrong with basics. I want the userLabels object to be accessed using jQuery and the result should be an array, so I can perform the jQuery.inArray() operation.
Firstly, here's how you can access dataset using the method you have.
var dataset =
{
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
};
alert(dataset['person'][0]['userLabels']); //style 1
alert(dataset.person[0]['userLabels']); //style 2
alert(dataset.person[0].userLabels); //style 3
//Also you can use variables in place of specifying the names as well i.e.
var propName ='userLabels';
alert(dataset.person[0][propName]);
//What follows is how to search if a value is in the array 'userLabels'
$.inArray('Name', dataset.person[0].userLabels);
I'd like to ask why you're doing this in a such an 'interesting way'. Why don't you just make them all objects?
That's what I would do if I were you because if you think about it, a person IS an object and it should be noted that arrays are basically objects in Javascript with a 'length' property, though I won't elaborate on it here (feel free to do some research though). I'm guessing it's because you don't know how to iterate over object properties. Of course if it makes more sense to you, go for it.
Note one of the differences between an array and an object is that object properties need to be defined; you'll notice that I gave 'Name' and 'Role' values of 'undefined' below.
In any case, here is what I would do:
var dataset =
{
"person" : {
"userLabels": {"Name" : undefined,"Role": undefined},
"tagNames": {"lName" : undefined,"role" : undefined},
"tableClass": "width530",
"colWidths": ["50%","50%"]
}
};
for (var i in dataset) { //iterate over all the objects in dataset
console.log(dataset[i]); //I prefer to use console.log() to write but it's only in firefox
alert(dataset[i]); // works in IE.
}
//By using an object all you need to do is:
dataset.person.userLabels.hasOwnProperty('Role'); //returns true or false
Anyways, hope this helps.
var basic = dataset.person[0].userLabels;
// | | |
// | | --- first element = target object
// | --- person property
// ---- main-object
var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
doStuff();
}

Categories