I am trying to update single value(ElementStatus) in below mentioned multidimentional JSON file.
BuildingID: 1521
BuildingName: "PEN LLOYD BUILDING"
BuildingNumber: "A"
ElementList: Array(15)
0: {ElementID: 114, SurveyTypeID: 3, Code: "M.01.01.01", ElementDescription: "M.01.01.01 Boilers/Plant", ElementStatus: "null"}
1: {ElementID: 115, SurveyTypeID: 3, Code: "M.01.01.02", ElementDescription: "M.01.01.02 Heat Emitters", ElementStatus: "null"}
2: {ElementID: 116, SurveyTypeID: 3, Code: "M.01.01.03", ElementDescription: "M.01.01.03 Distribution", ElementStatus: "completed"}
Here is the code
var newData=JSON.parse(success);
const data1 = newData[0].results.recordset[0].ElementList;
//console.log(data1.toArray());
var array=JSON.parse(data1)
array.forEach(function(element){
if(element.ElementDescription==elementsName)
{
element.ElementStatus="completed"
}
})
newData[0].results.recordset[0].ElementList=array
After iterating through forEach loop,I m getting ElementList in Array format.
But I want it in string format that is how it was earlier.
There are a number of problems with the code you show. The data you show is not in proper JSON format, so that will fail right off of the bat.
I have reworked your example to show proper input with JSON output.
let elementsName = "M.01.01.01 Boilers/Plant";
let success = `{"BuildingID": 1521,
"BuildingName": "PEN LLOYD BUILDING",
"BuildingNumber": "A",
"ElementList":
[{"ElementID": 114, "SurveyTypeID": 3, "Code": "M.01.01.01", "ElementDescription": "M.01.01.01 Boilers/Plant", "ElementStatus": null},
{"ElementID": 115, "SurveyTypeID": 3, "Code": "M.01.01.02", "ElementDescription": "M.01.01.02 Heat Emitters", "ElementStatus": null},
{"ElementID": 116, "SurveyTypeID": 3, "Code": "M.01.01.03", "ElementDescription": "M.01.01.03 Distribution", "ElementStatus": "completed"}]}`;
let newData=JSON.parse(success);
newData.ElementList.forEach(function(element){
if(element.ElementDescription==elementsName)
{
element.ElementStatus="completed"
}
});
let outputString = JSON.stringify(newData);
console.log(outputString);
Related
I recently got interested on using the spread operator syntax, so I tried some examples, I have this example of array:
var entities = [
{
"id": 1,
"age": 33,
"hobby": "games"
},
{
"id": 2,
"age": 28,
"hobby": "chess"
},
{
"id": 3,
"age": 21,
"hobby": "comics"
},
{
"age": 23,
"hobby": "games"
}
]
Then, to update all hobbies at "once" I do the following:
entities.forEach(function(entity, index) {
this[index] = {...entity, hobby: "Some String to update all hobbies"};
}, entities);
console.log(entities)
Which works but I was wondering if there's a more efficient or shorter way to achieve it while using the spread operator. Any suggestions?
EDIT:
forEach is not necessary for me, or even do it in that way, I was curious on whether the spread syntax could be used (or not) to update nested values
The spread operator doesn't really help when you're updating the list, like you do in your example. It's easier to just update the property of each object:
var entities = [ { "id": 1, "age": 33, "hobby": "games" }, { "id": 2, "age": 28, "hobby": "chess" }, { "id": 3, "age": 21, "hobby": "comics" }, { "age": 23, "hobby": "games" } ]
entities.forEach(entity => {
entity.hobby = "Some String to update all hobbies";
});
console.log(entities)
The spread operator is useful if you want to create copies of objects, like you might want to do in a .map:
var entities = [ { "id": 1, "age": 33, "hobby": "games" }, { "id": 2, "age": 28, "hobby": "chess" }, { "id": 3, "age": 21, "hobby": "comics" }, { "age": 23, "hobby": "games" } ]
const newEntities = entities.map(entity =>
({...entity, hobby: "Some String to update all hobbies"})
);
console.log(newEntities)
The spread operator will iterate over all keys in the object to copy them and their values into the new object. If you want more efficiency, don't use the spread operator. Just assign directly to each object as you iterate over the list:
entity.hobby = "Some String to update all hobbies"
Note that this modifies the object in the existing array. So you don't need to assign this[index]. Alternatively, you can use map() instead of foreach() to return a new array that is created from the existing array.
Not sure if spread operator is really needed for what you are doing?
You can also look into this link for some interesting usage of the spread, Array.from and rest operator.
More into just spread operator here.
If you are looking for a fancier/smaller way to write this, here's two, one that uses uses .map and spread to return a copy of entities, and another that uses .forEach and updates the same array entities:
const COMMON_HOBBY = 'Coding';
let entities = [{
"id": 1,
"age": 33,
"hobby": "games"
},
{
"id": 2,
"age": 28,
"hobby": "chess"
}];
// To assign to new array (copy)
let output = entities.map((entity) => ({...entity, hobby: COMMON_HOBBY }));
console.log(output);
// Mutate /edit same array entities
entities.forEach((entity) => entity.hobby = COMMON_HOBBY );
console.log(entities);
I'm practicing how to maniupulate data in JS in this article: http://learnjsdata.com/combine_data.html
var articles = [
{"id": 1, "name": "vacuum cleaner", "weight": 9.9, "price": 89.9, "brand_id": 2},
{"id": 2, "name": "washing machine", "weight": 540, "price": 230, "brand_id": 1},
{"id": 3, "name": "hair dryer", "weight": 1.2, "price": 24.99, "brand_id": 2},
{"id": 4, "name": "super fast laptop", "weight": 400, "price": 899.9, "brand_id": 3}
];
var brands = [
{"id": 1, "name": "SuperKitchen"},
{"id": 2, "name": "HomeSweetHome"}
];
articles.forEach(function(article) {
var result = brands.filter(function(brand){
return brand.id === article.brand_id;
});
delete article.brand_id;
article.brand = (result[0] !== undefined) ? result[0].name : null;
});
I'm confused with the last part: article.brand = (result[0] !== undefined) ? result[0].name : null;
I understand the conditional operation: it wants to have null value if result[0] is not defined. But I'm wondering what result[0] refers to. I thought it would take first object: {"id":2, "name": "HomeSweetHome"} so there should be for loop to iterate all objects in order to see if objects meet the condition? Could you inform me what I'm missing or/and what result[0] refers to?
Thanks,
result[0] will be undefined in case there is no element in result. result is expected to be an array of brands filtered by the filter operation
The filtered array result will have same brand as that of the current article in the outer foreach loop. The filter condition is going to achieve that.
It looks like in this particular case you will get only one element in result array always as there are unique brand ids. It might have more elements in case of duplicated brand ids.
result[0] points to first element in the array result
I have a JSON stringified object as:
{
"lesseeName": "Padyster-7",
"lesseeRegNo": "12345",
"lesseeVatNo": "4456",
"telFaxNo": "1234567891",
"billingAddress": {
"addressId": null,
"addressLine1": "XYz , l1 street",
"addressLine2": "near xyz bank",
"postalCode": "60000",
"countryName": "MY",
"cityName": "Kuala lumpur",
"stateProvinceCode": "Kuala lumpur"
},
"mlaList": [{
"mlaNo": 92,
"lesseeId": 108,
"executionDate": "27/01/2017",
"signatoryInfo": "Test",
"overdueRate": 3.44,
"nonPaymentDays": 2,
"consolidationTerm": "Monthly",
"createdBy": null,
"createdDtm": null,
"updatedBy": null,
"updatedDtm": null,
"statusIndicator": null,
"signatoryEmail": "tooot#gmail.com",
"leaseMlaNo": "OPM1",
"statusDescription": "APPROVED"
}, {
"mlaNo": 93,
"lesseeId": 108,
"executionDate": "03/01/2017",
"signatoryInfo": "tess",
"overdueRate": 5.77,
"nonPaymentDays": 2,
"consolidationTerm": "Bi-Monthly",
"createdBy": null,
"createdDtm": null,
"updatedBy": null,
"updatedDtm": null,
"statusIndicator": null,
"signatoryEmail": "xyz#gmail.com",
"leaseMlaNo": "OPM2",
"statusDescription": "APPROVED"
}]
}
I am working in Reactjs and I want my object to be iterated such that the inner array mlaList of objects gets iterated to display value one after other.
whenever I try using the .map function to the parent object I get an error saying ".map is not a function" below is the iteration I attempt which fails:
{data.map((data, index) => {data.leaseMlaNo} {data.signatoryEmail})}
I have referred to the SO questions quite similar to this one, but they just talk about iterating the objects using Object.keys
Please help me understand what I am doing wrong and what should be the correct way to achieve this
The method Array#map is a method of the Array class, and not of the Object class. However, the mlaList property is an array, and you can iterate it. You should use data.mlaList.map():
// if the data is stringified - const data = JSON.parse({ the object });
const data = {"lesseeName":"Padyster-7","lesseeRegNo":"12345","lesseeVatNo":"4456","telFaxNo":"1234567891","billingAddress":{"addressId":null,"addressLine1":"XYz , l1 street","addressLine2":"near xyz bank","postalCode":"60000","countryName":"MY","cityName":"Kuala lumpur","stateProvinceCode":"Kuala lumpur"},"mlaList":[{"mlaNo":92,"lesseeId":108,"executionDate":"27/01/2017","signatoryInfo":"Test","overdueRate":3.44,"nonPaymentDays":2,"consolidationTerm":"Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"tooot#gmail.com","leaseMlaNo":"OPM1","statusDescription":"APPROVED"},{"mlaNo":93,"lesseeId":108,"executionDate":"03/01/2017","signatoryInfo":"tess","overdueRate":5.77,"nonPaymentDays":2,"consolidationTerm":"Bi-Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"xyz#gmail.com","leaseMlaNo":"OPM2","statusDescription":"APPROVED"}]};
const result = data.mlaList.map((o, index) => o.signatoryEmail); // in react <div key={index}>{o.signatoryEmail}</div> for example
console.log(result);
array.prototype.map is an array function, not for objects so you would want to call it on your mlalist key:
const data = {"lesseeName":"Padyster-7","lesseeRegNo":"12345","lesseeVatNo":"4456","telFaxNo":"1234567891","billingAddress":{"addressId":null,"addressLine1":"XYz , l1 street","addressLine2":"near xyz bank","postalCode":"60000","countryName":"MY","cityName":"Kuala lumpur","stateProvinceCode":"Kuala lumpur"},"mlaList":[{"mlaNo":92,"lesseeId":108,"executionDate":"27/01/2017","signatoryInfo":"Test","overdueRate":3.44,"nonPaymentDays":2,"consolidationTerm":"Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"tooot#gmail.com","leaseMlaNo":"OPM1","statusDescription":"APPROVED"},{"mlaNo":93,"lesseeId":108,"executionDate":"03/01/2017","signatoryInfo":"tess","overdueRate":5.77,"nonPaymentDays":2,"consolidationTerm":"Bi-Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"xyz#gmail.com","leaseMlaNo":"OPM2","statusDescription":"APPROVED"}]};
const list = data.mlaList.map(val => `${val.leaseMlaNo} ${val.signatoryEmail}`);
console.log(list)
I have the following JSON Object which I want to copy/clone.
While cloning I want only a few specific keys, say id, measurement_tag_id and unit.
Following is my JSON object:
{
"id": 246,
"measurement_profile_id": 52,
"measurement_tag_id": 339,
"unit": "in",
"value": 5,
"measurement_tag": {
"id": 339,
}
...
...
...
...many more keys...
}
How can I achieve this in coffeescript, using only one liners?
This is very simple to do with a for loop:
new_object = {}
new_object[key] = old_object[key] for key in ["id", "measurement_tag_id", "unit"]
when my ajax call completes an array of json is returned
for my angular data binding to work perfectly, i need to merge all values in to a single JSON file. I have tried $.extend(), it's giving following output
Need a solution for this
for example if my response looks like this:
[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];
the output i need is :
{ test':'test', 'test':'test', 'test':'test', 'test':'test' }
Edit:
The final value will be associated to the ng-model automatically.
desired output example:
{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8
}
From what I understand you are trying to convert array of Json data into one singel json data. So you have array of values but you would want all of them in one variable. Try this
var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];
var finalData ="";
$.each(testData,function(index,value){
finalData += value +',';
});
finalData = finalData.replace(/\},\{/g,',').slice(0, -1);
document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Map just applies the function to every element in the array.
var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)
If you use underscore.js then can easily
like:
var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
var newList = _.extend.apply(null,[{}].concat(list));
then output will be
{ test1: "test1", test2: "test2", test3: "test3" }
Iterate over the array, convert every value to a JSON object, concatenate and then convert to a string back.
If you need fo this more times, you probably should make this a function.