Related
How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.
var params1 = {
spreadsheetId: '1g9y32IkyujOupw6O6eRhtlCcwhn5vv9mM_Yr4peRRmo',
range: str,
};
var clearValuesRequestBody = {
};
var request = await gapi.client.sheets.spreadsheets.values.clear(params1, clearValuesRequestBody);
Above code is to delete a row from the google sheet. Now, my question is that how to remove that blank row from the google sheet by moving rest of the rows?
Answer:
You need to use a batchUpdate to do this.
Request Example:
{
"requests": [
{
"deleteDimension": {
"range": {
"sheetId": sheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 1
}
}
}
]
}
The above request will delete the first row from a sheet with given gid.
The rows are 0-indexed so starting at 0 and ending at 1 will delete the first row. Likewise, starting at 8 and ending at 18 will delete rows 9-18.
The method is as follows:
gapi.client.sheets.spreadsheets.batchUpdate(resource)
Note: This is spreadsheets.batchUpdate and NOT spreadsheets.values.batchUpdate.
All together now:
const resource = {
"requests": [
{
"deleteDimension": {
"range": {
"sheetId": sheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 1
}
}
}
]
}
const response = gapi.client.sheets.spreadsheets.batchUpdate({
"spreadsheetId": "your-spreadsheet-id",
"resource": resource
})
.then(function(response) {
console.log("Response is: \n", response)
}, function(err) {
console.error("Execute error", err)
})
In order to get which rows are blank, you will have to use spreadsheets.values.get and manually loop through the response.
The response will be of the following form; you will need to loop through response.values:
{
"range": "Sheet1!A1:Z1000",
"majorDimension": "ROWS",
"values": [
[] // each row is an array
]
}
In this example I am using a Spreadsheet that looks like this:
For this spreadsheet, response will be:
{
"range": "Sheet1!A1:Z1000",
"majorDimension": "ROWS",
"values": [
[ "1", "1", "1", "1", "1", "1", "1", "1", "1", "1" ],
[ "2", "2", "2", "2", "2", "2", "2", "2", "2", "2" ],
[ "3", "3", "3", "3", "3", "3", "3", "3", "3", "3" ],
[ "4", "4", "4", "4", "4", "4", "4", "4", "4", "4" ],
[],
[ "6", "6", "6", "6", "6", "6", "6", "6", "6", "6" ],
[],
[],
[ "9", "9", "9", "9", "9", "9", "9", "9", "9", "9" ],
[ "10", "10", "10", "10", "10", "10", "10", "10", "10", "10" ],
]
}
so we just need to check what elements of response.result.values are empty arrays:
Assume that the Spreadsheet has columns up to ZZZ so to encapulate the whole range, you can make the request:
const emptyRows = []
gapi.client.sheets.spreadsheets.values.get({
"spreadsheetId": "your-spreadsheet-id",
"range": "A:ZZZ"
})
.then(function(response) {
response.result.values.forEach(function(row, index) {
if (row.length == 0) emptyRows.push(index)
})
}, function(err) {
console.error("Execute error", err)
})
and then loop through this array backwards, passing the values into the previous batchUpdate request to completely remove them from the sheet. It's important delete from bottom up so to not change row numbers and accidentally delete rows with data in them.
Note: this will not delete empty rows past the last data row, only empty rows within the data set.
References:
Method spreadsheets.batchUpdate | Sheets API | Google Developers
Row and Column Operations | Sheets API | Google Developers
Method: spreadsheets.values.get | Sheets API | Google Developers
I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.
Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.
I am not sure whether I am using the correct approach. This is what I have try:
var newJsonID = _.pluck(newJson, 'id');
var currentJsonID = _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);
Expected Final Outcome:
[
{
"id": "12",
"property1Name": "1"
"status": "inactive"
},
{
"id": "11",
"property1Name": "1"
"status": "inactive"
},
{
"id": "10",
"property1Name": "1"
"status": "inactive"
},
{
"id": "9",
"property1Name": "1"
"status": "active"
}
]
A solution in plain Javascript with two loops and a hash table for lookup.
function update(newArray, currentArray) {
var hash = Object.create(null);
currentArray.forEach(function (a) {
hash[a.id] = a.status;
});
newArray.forEach(function (a) {
a.status = hash[a.id] || 'inactive';
});
}
var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');
I'm trying to sort the json below, but until now couldn't find the way. I get this json by jQuery ajax with datatype json. How can I apply sort to this keeping the index? Every time i try to sort javascript throws an error telling undefined is not a function. I already know that json or objects don't have sort.
So how can I achieve this? I really need to keep this index.
{
"header": {
"user": "1059",
"authenticated": true,
"isGuest": false,
"time": 1416362117
},
"batches": {
"3503": { // Preserve this index
"user": "1059",
"auction": "1826",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415379600",
"date_end": "1417021200", // Sort by this value
},
"3583": {
"user": "1059",
"auction": "1886",
"auto_value": "0.00",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415376000",
"date_end": "1417017600",
},
}
}
As I wrote and cited in comments - properties do not have an order. Make an array of single-property objects, which you can sort. Something like this:
var data = {
"header": {
"user": "1059",
"authenticated": true,
"isGuest": false,
"time": 1416362117
},
"batches": [ // this is an array of objects, not a single object
{"3503": { // Preserve this index
"user": "1059",
"auction": "1826",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415379600",
"date_end": "1417021200", // Sort by this value
}},
{"3583": {
"user": "1059",
"auction": "1886",
"auto_value": "0.00",
"number": "1",
"published": "1",
"type": "1",
"status": "1",
"date_start": "1415376000",
"date_end": "1417017600",
}}
] // end of array
}
data.batches.sort(function(a, b) {
return a[Object.keys(a)[0]].date_end - b[Object.keys(b)[0]].date_end;
});
console.log(data.batches);
And you can keep those numbers inside of the object containing user, auction and so on for easier access.
I always think it's going to be easy... I plan to use the json below to build router objects. I put a console.log and so I could have a break point spot so I could try to figure out how to access the the object properties from the chrome console. It never goes into the for loop though.
The main question is how to properly turn the JSON into objects and how to access it's properties.
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('JSON/data.json', function(json) {
for (var i=0;i<json.length;i++){
console.log("in for loop");
}
});
});
</script>
{
"_id": {
"$oid": "4f91f2c9e4b0d0a881cf86c4"
},
"DSC21": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
},
"DSC22": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
},
"DSC23": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
},
"DSC24": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
}
}
The variable json is already an object, but it is not an array, so a typical for-loop is insufficient. Since json.length is undefined, i<json.length fails on the first iteration and you skip over the loop.
for (var key in json) {
// key is your DSCxxx
// json[key] is the corresponding object
}
JSON is natively available in JavaScript, you traverse it like you would traverse any object or array.
json["DSC21"]["Router"]["online"][0]; // 1
json.DSC21.Router.online[0]; // equivalent
json.DSC21.Router.online.0; // INCORRECT
If you don't know the names of the properties and want to loop through them use the for .. in construction:
for (var key in json) {
console.log(key); // _id, DSC21, DCS22 etc..
console.log(json[key]); // { "$oid": "" }, { "Router": ".." } etc.
}
This does leave the hasOwnProperty issue, but it shouldn't be a problem if you're just reading JSON data.
maybe you want to know how to iterate your objects?
here would be how to do that:
for( var key in json ){
if( key != '_id'){
var router = json[key].Router;
for( var i = 0; i < router.online.length; i++ ){
console.log(i + ' is online: ', router.online[i]==1?'true':'false');
}
etc...
}
}