Creating an array of objects inside an object that already exists - javascript

I can create nested objects in Javascript like this:
var filter = {
filterColumns: {
value: "",
valueText:""
}
};
but how can I turn filtercolumns into an array of objects? for example I would like to be able to do this:
filter.filterColumns[26].value = "value"
filter.filterColumns[26].valueText = "Bob"
filter.filterColumns[32].value = "value"
filter.filterColumns[32].valueText = "Ibb"
etc.
Thanks
EDIT: Apologies, I got this completely wrong. My original post confused javascript with C#. I have re-written it to reflect what I am trying to do.

Do you mean something like the following?
var filter = {
filterColumns: [
{
value: "1",
valueText: "Alice"
},{
value: "2",
valueText: "Bob"
},{
value: "3",
valueText: "Charlie"
}
]
};
Now filter.filterColumns[1].valueText would contain the string "Bob";
You can for example add to the list with the following code:
filter.filterColumns.push({value: "4", valueText: "Daniel"});

Related

ReactJS - Convert JSON Array

I need help for simple question, to convert this:
{
"data": [{
"data_1": {
"name": "name1",
"value": "value1"
},
"data_2": {
"name": "name2",
"value": "value2"
}
}]
}
To this:
I need help for simple question, to convert this:
{
"data": {
"data_1": {
"name": "name1",
"value": "value1"
},
"data_2": {
"name": "name2",
"value": "value2"
}
}
}
Need to remove '[]'.
Thanks a lot!
If I understand you correctly, it's easy enough. You just need to return 0 element from data array.
Here is an example in JavaScript:
const original = {
data: [{
data_1: {
name: "name1",
value: "value1"
},
data_2: {
name: "name2",
value: "value2"
}
}]
};
const converted = {
data: original.data[0]
};
Ideally you want to make a deep copy of those inner objects, and create a new object with them. There are many ways to do this but one of the easiest methods is to stringify them (ie the first element of the array), and then parse that string. That way new references are built, and changes to the original data won't have an effect on the new data.
const data={data:[{data_1:{name:"name1",value:"value1"},data_2:{name:"name2",value:"value2"}}]};
// Stringify, and then parse the string
const copy = (o) => JSON.parse(JSON.stringify(o));
// Assemble the new object by copying the part
// for reuse
const out = { data: copy(data.data[0]) };
// Check that changes made to the original object
// are not reflected in the new object
data.data[0].data_1.name = 'bob';
console.log(out);

How to pull a property like "customer.gender" from an array of object with map [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 4 years ago.
I am using javascript map to loop through an array of object. Today i have to loop through an array of object which looks like,
averageReport = [
{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
What i tried to get only the "customer.gender",
averageReport
.map(x => console.log(x.customer.gender)
)
I get the error "Cannot read property 'gender' of undefined"
code on stackblitz
Try,
averageReport
.map(x => console.log(x["customer.gender"])
Since you named your key customer.gender you can't use dot-notation to get the value, you have to use bracket notation ([]).
Also mapping to console.log() doesn't make much sense (since console.log() returns undefined, you are creating a new array of undefined when using map() here), just use forEach():
averageReport = [{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
averageReport.forEach(x => console.log(x["customer.gender"]));
If you want to access the property using dot-notation, you have to make customer an object and gender a property of it, like so:
averageReport = [{
"result": 150.54909908933223,
"customer": {
"gender": "Female"
}
},
{
"result": 150.35230422844595,
"customer": {
"gender": "Male"
}
}
];
Use bracket notation for accessing the customer.gender property. Try the following :
var averageReport = [ { "result": 150.54909908933223, "customer.gender": "Female" }, { "result": 150.35230422844595, "customer.gender": "Male" } ];
var result = averageReport.map(x =>x["customer.gender"]);
console.log(result);

Editing an object in nested data structure

I have a data structure like this:
var fieldTmp= [{
"CountryDetails":[{
"countryName":"Kerala",
"JobDetails":[{
"RequisitionId":"00020447961",
"City":"KOCHI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"26103",
"City":"TRIVANDRUM",
"PostedDate":"2016-12-12"
},{
"RequisitionId":"26077",
"City":"ALAPPEY",
"PostedDate":"2016-10-09"
},{
"RequisitionId":"00020774701",
"City":"KOTTAYAM",
"PostedDate":"2016-06-12"
},{
"RequisitionId":"26078",
"City":"ADOOR",
"PostedDate":"2016-05-19"}]
},
"countryName":"MADRAS",
"JobDetails":[{
"RequisitionId":"0025456",
"City":"CHENNAI",
"PostedDate":"2017-06-05"
},{
"RequisitionId":"69847562",
"City":"ADYAR",
"PostedDate":"2016-10-14"}]
},
{"countryName":"Tamil Nadu",
"JobDetails":[{
"RequisitionId":"00020550501",
"City":"CHENNAI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"00020786022",
"City":"KOVAI",
"PostedDate":"2016-09-01"
},{
"RequisitionId":"00020786071",
"City":"TRICHY",
"PostedDate":"2016-04-10"}]
}] }]
My requirement is, I need to add Job Details under MADRAS to Tamil Nadu and I need to sort the data based on one property -PostedDate.
So my result should be something like,
var fieldTmp= [{
"CountryDetails":[{
"countryName":"Kerala",
"JobDetails":[{
"RequisitionId":"00020447961",
"City":"KOCHI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"26103",
"City":"TRIVANDRUM",
"PostedDate":"2016-12-12"
},{
"RequisitionId":"26077",
"City":"ALAPPEY",
"PostedDate":"2016-10-09"
},{
"RequisitionId":"00020774701",
"City":"KOTTAYAM",
"PostedDate":"2016-06-12"
},{
"RequisitionId":"26078",
"City":"ADOOR",
"PostedDate":"2016-05-19"}]
},
{"countryName":"Tamil Nadu",
"JobDetails":[{
"RequisitionId":"0025456",
"City":"CHENNAI",
"PostedDate":"2017-06-05"
},{
"RequisitionId":"00020550501",
"City":"CHENNAI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"69847562",
"City":"ADYAR",
"PostedDate":"2016-10-14"
},{
"RequisitionId":"00020786022",
"City":"KOVAI",
"PostedDate":"2016-09-01"
},{
"RequisitionId":"00020786071",
"City":"TRICHY",
"PostedDate":"2016-04-10"}]
}] }]
I tried to extract Madras data and add that to under Tamil Nadu. But nothing is working.
I know how to extract single or multiple value from JSON object. But I need to edit that JSON and sort it. That I am able to do it.
I got the solution.
When the countryName is "Tamil Nadu" and "MADRAS",I extracted all the data and saved it in a new array using below code.
function mergingBothStateDetails(jsonJobDetails){
for(var j=0;j<jsonJobDetails.length;j++)
{
newTmpRecord.push({"RequisitionId":jsonJobDetails[j].RequisitionId,
"PostedDate":jsonJobDetails[j].PostedDate,
"City":jsonJobDetails[j].City});
}
}
Here newTmpRecord is an Array and is like universal variable
For sorting I used below codes
function sortNewList(){
newTmpRecord.sort(function(a, b){ // sort object by retirement date
var dateA=new Date(a.PostedDate), dateB=new Date(b.PostedDate)
return dateB-dateA //sort by date descending
});
}
You can simply extract the object "Madras" from the array and add all of its Jobdetails to the object "Tamil Nadu" in a for loop. You can either look where to add them in the loop by checking the dates, or you can write a sort function, which is pretty easy in javascript and well explained here:
You might want to look up objects
And here the sorting is explained.

Can't seem to delete element in object literal [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 6 years ago.
I have a JSON object literal from which I'm trying to delete an element (let's say apples). I've tried many things, but I just can't seem to get it to work.
var JSON = {
"fruits": [{
"name": "oranges",
"quantity": "3"
},{
"name": "apples",
"quantity": "2"
},{
"name": "bananas",
"quantity": "3"
}
]};
console.log(JSON);
delete JSON.fruits[1];
console.log(JSON);
Calling the above code results in the object being removed, but it looks like then inserts the key before the 3rd object. Have a look at this fiddle. I don't want that to happen.
That's what happens in the Fiddle. But then in my live script however, it looks like it replaces the deleted object with the word null which breaks my script.
I've also tried many variations of .splice() but that seems to be for arrays, rather than object literals.
Any ideas?
You could use Array#splice for the array inside of the object.
delete deletes the object, but you get an undefined element of the array.
var object = { fruits: [{ name: "oranges", quantity: "3" }, { name: "apples", quantity: "2" }, { name: "bananas", quantity: "3" }] };
object.fruits.splice(1, 1);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
JSON.fruits.splice(1, 1); // to remove apples
Knowledge: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Simplify an associative array

I'm hitting an api built using CakePHP. Cake returns its objects like this:
[
{
"Note": {
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
}
},
{
"Note": {
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
}
]
What I want to do is take that result and basically get rid of the keys. Something like this:
[
{
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
},
{
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
]
I'm basically just trying to make it easier to reference this in Angular. I need to do this on the client side. Any ideas?
You could refactor it like so:
var json = '[{"Note":{"id":"1","clas":"test","obj_id":null,"note":"test"}},{"Note":{"id":"2","clas":"another","obj_id":null,"note":"another"}}]';
var obj = JSON.parse(json);
var arr = [];
for (i = 0; i < obj.length; i++)
{
arr.push(obj[i].Note);
}
Working example here
(Note also that if your key value 'Note' isn't always the same, this will change dramatically. It's likely that 'Note' isn't going to be the same in each instance either; that would generate an improperly keyed object. Alternatively, if you always need the first object in the array, you could use obj[i][0] instead).
(More note if you're using cakephp, this would be much easier done using Hash::, but if you need to do it client side, this is the solution).

Categories

Resources