Answer the question
In order to leave comments, you need to log in
How to split data into cells from a nested list?
Good afternoon.
Can you please tell me how to take data from an array with an attachment and spread it into cells?
For example, there is such json
response = {
"result": {
"items": [
{
"product_id": 253611,
"offer_id": "УТ-00007992",
"stock": {
"coming": 0,
"present": 0,
"reserved": 0
}
},
{
"product_id": 253616,
"offer_id": "УТ-00007043",
"stock": {
"coming": 0,
"present": 1,
"reserved": 1
}
}
],
"total": 20
}
}
{"product_id":253611,"offer_id":"УТ-00007992","stock":{"coming":0,"present":0,"reserved":0}
( and split its values into 5 cells. let arr = JSON.parse(response)['result']['items'];
let data = [];
arr.forEach((el) => data.push(Object.values(el)));
SpreadsheetApp.getActive()
.getSheetByName('имя')
.getRange(1, 1, data.length, data[0].length)
.setValues(data);
Answer the question
In order to leave comments, you need to log in
You need a process for flattening objects. Google the term "flatten".
For the current specification of Google Apps Script, you can try using the following code
/**
* @see https://gist.github.com/penguinboy/762197#gistcomment-3448642
*/
function flatten(object, path = null, separator = '.') {
return Object.keys(object).reduce((acc, key) => {
const value = object[key];
const newPath = Array.isArray(object)
? `${path ? path : ''}[${key}]`
: [path, key].filter(Boolean).join(separator);
const isObject = [
typeof value === 'object',
value !== null,
!(value instanceof Date),
!(value instanceof RegExp),
!(Array.isArray(value) && value.length === 0),
].every(Boolean);
return isObject
? { ...acc, ...flatten(value, newPath, separator) }
: { ...acc, [newPath]: value };
}, {});
}
/**
*
*/
function myFunction() {
const response = {
result: {
items: [
{
product_id: 253611,
offer_id: 'УТ-00007992',
stock: {
coming: 0,
present: 100,
reserved: 23,
},
},
{
product_id: 253616,
offer_id: 'УТ-00007043',
stock: {
coming: 0,
present: 23231,
reserved: 1,
},
},
],
total: 20,
},
};
const arr = response['result']['items'];
const data = [];
arr.forEach((el) => data.push(Object.values(flatten(el))));
SpreadsheetApp.getActive()
.getSheetByName('имя')
.getRange(1, 1, data.length, data[0].length)
.setValues(data);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question