How to compare a value with each item of range - javascript

for the last 3 days (my first 3 days of coding) i've been trying to code an script to get my google contacts that have certain keyword, it being "Catamarca", on their name and also to delete that keyword after they've been added to the spreadsheet leaving only their name.
I've been succesfull in all of this. But now i want to only run the script on an existing database, and only run it if the new contacts are not on the sheet already, and not write over the existing ones.
Here is my code so far:
function impContacts() {
// variables
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GContacts");
var grupo = ContactsApp.getContactGroupById("http://www.google.com/m8/feeds/groups/email#gmail.com/base/6")
const contactos = grupo.getContacts();
const arraycontacts = [];
// get the last row on B with data on it
const lastRow = sheet.getLastRow();
const Avals = sheet.getRange("B2:B" + lastRow).getValues();
const Alast = lastRow - Avals.reverse().findIndex(c => c[0] != '');
Logger.log(Alast);
var rangeInteres = sheet.getRange(2, 1, Alast, sheet.getLastColumn()).getValues();
// look for contacts that has in their name the word "Catamarca", and save them with their id, name and phone.
contactos.forEach(contacto => {
var phone = ""
if (contacto.getPhones()[0]) {
phone = contacto.getPhones()[0].getPhoneNumber()
};
var name = ""
if (contacto.getFullName().match("Catamarca")){
name = contacto.getFullName();
};
var idcont = ""
if (name == rangeInteres.forEach(namme =>
{
oldName = namme[1];
Logger.log(oldName);}))
{
idcont =
rangeInteres.forEach(id => {
oldId= id[0];
Logger.log(oldId);})
}
else
{
idcont = contacto.getId().replace(/\D/g, '')
};
const datoscont = [idcont, name, phone];
arraycontacts.push(datoscont);
})
// save new contact
sheet.getRange(2, 1, arraycontacts.length, 3).setValues(arraycontacts);
// look for "catamarca"
range = sheet.getRange("B2:B")
var textFind = range.createTextFinder("Catamarca");
textFind.matchEntireCell(false);
textFind.ignoreDiacritics(true);
textFind.matchCase(false);
var textFound = textFind.findNext();
// Si encuentra coincidencia reemplazar por ""
if (textFound !== null) {
var vals = textFound.getValues();
textFind.replaceAllWith("");
}
}
What i need to keep the most is the ID of the existing contacts (the IDs are different from the ones coming from google contacts but the names are the same), because they are linked to an app created using AppSheet.
I believe there should be a way to accomplish this by editing this part of the code
var idcont = ""
if (name == rangeInteres.forEach(namme =>
{
oldName = namme[1];
Logger.log(oldName);}))
{
idcont =
rangeInteres.forEach(id => {
oldId= id[0];
Logger.log(oldId);})
}
else
{
idcont = contacto.getId().replace(/\D/g, '')
};
In my head and with my current knowledge, the code should be working, but it's not, I mean, it runs, but overwrites everything.

Related

Method search on google sheet data from one column using google script?

I had tried to search data like below flow picture and script to search data from google sheet using google app script but the script using is not working properly but can someone tell me how to setup search function to find data like flow on image? thanx
[Flow searching data][1]
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Search", functionName: "searchRecord"} ];
ss.addMenu("Commands", menuEntries);
}
function searchRecord()
{
var ss = SpreadsheetApp.getActiveSpreadsheet()
var wsSearchingData = ss.getSheetByName("Searching Data")
var wsDatabase = ss.getSheetByName("Database")
var searchString = wsSearchingData.getRange("E4").getValue();
var column =1; //column Index
var columnValues = wsDatabase.getRange(2, column, wsDatabase.getLastRow()).getValues(); //1st is header row
var searchResult = columnValues.findIndex(searchString); //Row Index - 2
var searchValue = wsDatabase.getRange("B2:B2041").getValues()
var matchingDatabase = searchValue.map(searchColumn => {
var matchColumn = columnValues.find(r => r[0] == searchColumn[0])
return matchColumn = matchColumn ? [matchColumn[2]] : null
})
console.log(matchingDatabase)
if(searchResult != -1)
{
//searchResult + 2 is row index.
SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 1, 1))
}
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i] == search) return i;
wsSearchingData.getRange("B11").setValue(search[0]);
wsSearchingData.getRange("C11").setValue(search[1]);
wsSearchingData.getRange("D11").setValue(search[2]);
wsSearchingData.getRange("E11").setValue(search[3]);
wsSearchingData.getRange("F11").setValue(search[4]);
return;
}
}
[1]: https://i.stack.imgur.com/HF9K8.png
var searchResult = columnValues.findIndex(searchString); //Row Index - 2
replace the above code with:
var searchResult = columnValues.filter(r=>r[1]==searchString)
You can then put searchResult directly as output in the sheet. Make sure that [1] in the above contains the column index of Name in the columnValues Array.

GAS Function not setting value as intended in sheet

This is the Google Sheet, it can be copied: https://docs.google.com/spreadsheets/d/1ffIRGiGkiy5WFzSAvWNOY_3cqNXgTAOtO6o8vxS-BFU/edit?usp=sharing
The Function 'AddNewMembers' does not function, even if "isAdded == "No" it will not setValue(recruit_id)
function AddNewMembers(event){
event = {range: SpreadsheetApp.getActiveRange()}
CheckHandleSteamIDNotation(event)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var recruitment_log = ss.getSheetByName('RL1');
var main_roster = ss.getSheetByName('Main Roster');
var isAdded = recruitment_log.getRange('R3').getValue();
if(isAdded == "No") {
var recruit_id = "'" + recruitment_log.getRange('J3').getValue();
main_roster.getRange('I100').setValue(recruit_id);
}
}
function CheckHandleSteamIDNotation(event)
{
let formSheet = SpreadsheetApp.getActiveSheet();
let header = formSheet.getRange(1,1,1,formSheet.getMaxColumns()).getValues();
let formRange = formSheet.getRange(formSheet.getLastRow(), 1, 1, formSheet.getMaxColumns());
let formValues = formRange.getValues();
for(let i = 0; i < header[0].length; i++)
{
if(header[0][i].includes("SteamID"))
{
formValues[0][i] = "'" + formValues[0][i];
}
}
formRange.setValues(formValues);
}
Since the provided script above contains var isAdded = recruitment_log.getRange('R3').getValue(); the value of R3 is currently set to "Yes" that is why the condition for the script below is not running.
if(isAdded == "No") {
var recruit_id = "'" + recruitment_log.getRange('J3').getValue();
main_roster.getRange('I100').setValue(recruit_id);
}
Try this modification:
function AddNewMembers(event) {
event = { range: SpreadsheetApp.getActiveRange() }
CheckHandleSteamIDNotation(event)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var recruitment_log = ss.getSheetByName('RL1');
var main_roster = ss.getSheetByName('Main Roster');
//Gets all the data values on recruitment_log
var isAdded = recruitment_log.getRange(3, 1, recruitment_log.getLastRow(), recruitment_log.getLastColumn()).getValues();
//Gets the last row starting I17
var lastrow = main_roster.getRange(17, 9, main_roster.getLastRow() , 1).getValues().filter((x => x > 1)).length
//Sets the value on the last blank row
isAdded.map(x => x[17].toString().toLocaleLowerCase() == "no" ? "'" + main_roster.getRange(17 + lastrow,9).setValue(x[9]) : x)
}
I made modifications on your isAdded variable to the following to get the entire range of data on RL1 sheet.
var isAdded = recruitment_log.getRange(3, 1, recruitment_log.getLastRow(), recruitment_log.getLastColumn()).getValues();
This part of script was only used to get the current length of data for the New Operatives. Using .filter() method to filter out empty array elements, since getValues() gets blank cells if there is formatting applied on the spreadsheet.
var lastrow = main_roster.getRange(17, 9, main_roster.getLastRow() , 1).getValues().filter((x => x > 1)).length
Using ES6 .map() method to create a new array for the data that hasn't been added to the main roster sheet file.
isAdded.map(x => x[17].toString().toLocaleLowerCase() == "no" ? "'" + main_roster.getRange(17 + lastrow,9).setValue(x[9]) : x)
Screenshot:
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#description

Google sheet script to match and copy based from another adjacent cell

I am trying to look for matching cells in column R,T,and V in the reference table with column C in the main sheet. If there is a match then copy the assigned number in Q,S, and U and past it in column B next to the its match.
I have done the example manually.
Suggestion
Perhaps you can try this sample script:
Script [UPDATED]
function findMatch() {
var sh = SpreadsheetApp.getActiveSpreadsheet();
var lastRow = sh.getDataRange().getLastRow();
var reference = [];
var row = 1;
var data = sh.getRange("Q1:V"+lastRow).getDisplayValues().filter(function(x) {
return (x.join('').length !== 0);
});
sh.getRange("C1:C"+lastRow).getDisplayValues().forEach( x => {
reference.push([fixForUsage(x),row]);
row += 1;
});
reference.forEach(aisle => {
if(aisle[0] == "" || aisle[0].toString().toLowerCase().includes("aisle"))return;
data.forEach(match => {
var currentData = match[1] +"-"+match[3]+"-"+match[5];
if(currentData.includes(aisle[0])){
//get its number
if(match[1] == ""){
if(match[3] == ""){
if(match[5] == ""){
}else{
//if not empty
Logger.log("Find \""+aisle[0]+"\" from sheet row#"+aisle[1]+"\nRESULT:"+"\nFound a match on these data!: "+match+"\nHeader: \'"+data[0][4]+"\'\nNumber: "+match[4]);
pasteData(sh,aisle[1], data[0][4], match[4]);
}
}else{
//if not empty
Logger.log(+"Find \""+aisle[0]+"\" from sheet row#"+aisle[1]+"\nRESULT:"+"\nFound a match on these data!: "+match+"\nHeader: \'"+data[0][2]+"\'\nNumber: "+match[2]);
pasteData(sh,aisle[1],data[0][2],match[2]);
}
}else{
//if not empty
Logger.log("Find \""+aisle[0]+"\" from sheet row#"+aisle[1]+"\nRESULT:"+"\nFound a match on these data!: "+match+"\nHeader: \'"+data[0][0]+"\'\nNumber: "+match[0]);
pasteData(sh,aisle[1],data[0][0],match[0]);
}
}
});
});
}
function pasteData(sh,row, colAData, colBData){
sh.getRange("B"+row).setValue(colBData);
sh.getRange("A"+row).setValue(colAData);
}
function fixForUsage(x){ //This is to let the code know that e.q. 53-7 is 53-07
var part = x.toString().split("-");
if(part.length == 2 && part[1].length == 1){
return part[0]+"-0"+part[1];
}else{
return x;
}
}
Sample Sheet
Columns A, B, C:
Columns Q, R, S, T, U, V:
Sample Demonstration
After running the script from the Apps Script editor:
Apps Script editor log results for review:
Here is another solution (updated):
function myFunction() {
var sh = SpreadsheetApp.getActiveSheet();
// get all data
var data = sh.getRange('q2:v16').getDisplayValues();
var cols_QR = data.map(x => ({'crane': 'C5-1', 'seq': x[0], 'aisle': x[1]}));
var cols_ST = data.map(x => ({'crane': 'C5-4', 'seq': x[2], 'aisle': x[3]}));
var cols_UV = data.map(x => ({'crane': 'C5-2', 'seq': x[4], 'aisle': x[5]}));
data = [...cols_QR, ...cols_ST, ...cols_UV];
data = data.filter(x => x.aisle != '');
data.forEach((x,i) => data[i].aisle = fix(x.aisle)); // <--- new line
// create the object 'aisles'
var aisles = {}
for (let obj of data) aisles[obj.aisle] = {'crane': obj.crane, 'seq': obj.seq}
// get target range and target data
var target_range = sh.getRange('a2:c' + sh.getLastRow());
var target_data = target_range.getDisplayValues();
// fill target range with info from the 'aisles' object
for (let row in target_data) {
try {
let orig_key = target_data[row][2]; // <--- updated line
let key = fix(orig_key); // <--- new line
target_data[row] = [ aisles[key].crane, aisles[key].seq, orig_key ]; // <--- updated line
} catch(e) {}
}
// fill the target range with updated data
target_range.setValues(target_data);
}
// function to convert '10-1 1/4' --> '10-01', '8-0' --> '08-00', etc
function fix(key) {
return key.split(' ')[0]
.split('-').map(x => x.length == 1 ? '0' + x : x)
.join('-').slice(0,5);
}
Initial data:
Results:
Sheet
I decided don't add in my variant the function that makes true this: '53-7' == '53-07' and '11' == '11-0', etc, because I think it's a rather bad and error-prone idea. It will silently hide many errors in your data. But I can add it if you want.
Update
The function can be something like this:
function fix(key) {
return key.split(' ')[0]
.split('-').map(x => x.length == 1 ? '0' + x : x)
.join('-').slice(0,5);
}
// test
const keys = ['10-1 1/4', '11-0', '9-11 1/2', '8-0', '53-06', '52-7', '53-07', '104', '8-02-S', '08-01'];
keys.forEach(key => console.log(fix(key) + ' <--- ' + key));
I've added the function fix() and several lines to my original code.
But actually functions like this can cause additional troubles. For example I have no idea what means '104'? If it should be '10-04'? Or may be '01-04'? Or something else? You need be well prepared if you decide to play the risky game.
Note: you can change orig_key to key in this line:
target_data[row] = [ aisles[key].crane, aisles[key].seq, orig_key ];
This way you will get the 'fixed' values in the target table instead of original ones.

How to add a color stripe to every last row of a student attendance sheet using Google App Scripts?

As part of a student attendance system, I would like to add a color stripe to every last row of a class for attendance using App Scripts. My columns of Google Sheets are: (i) Date, (ii) Email, (iii) Latitude, (iv) Longitude, and (v) Subject-code. Tried many ways but did not find the solution.
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = sss.getId();
var sheetName = sss.getName();
var sheet = sss.getSheetByName("TempDataSet");
var sheet1 = sss.insertSheet('TempDataSet_temp');
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
var shID = sheet1.getSheetId().toString();
sheet1.getRange(2, 1, sheet.getLastRow() -1, sheet.getLastColumn()).sort({column: 1, ascending: false});
var columns_delete = [7,2]; //[7,5,4,2];
columns_delete.forEach(col=>sheet1.deleteColumn(col));
//const sss = SpreadsheetApp.getActiveSpreadsheet();
//const sheet = sss.getSheetByName("TempDataSet");
const subs = sheet.getRange('F2:F'+sheet.getLastRow()).getValues().flat();
const usubs = subs.filter((value, index, self)=>self.indexOf(value) === index);
const dts = sheet.getRange('A2:A'+sheet.getLastRow()).getDisplayValues().flat();
const udts = dts.filter((value, index, self)=>self.indexOf(value) === index);
if(usubs.length>1){
subs.forEach((s,i)=>{
if(i>1){
if(subs[i]!=subs[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
else if (udts.length>1){
dts.forEach((d,i)=>{
if(i>1){
if(dts[i]!=dts[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
var from = Session.getActiveUser().getEmail();
var subject = 'Batch Attendance Record for Your Reference';
var body = 'Dear Student,'+ '\n\n' + 'Greetings! Please find the batch attendance record attached. Stay safe and blessed.' + '\n\n' + 'Thank you.';
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID+"&gid="+shID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
sss.deleteSheet(sss.getSheetByName('TempDataSet_temp'));
var sheet2 = sss.getSheetByName('StudentList');
var data = sheet2.getLastRow();
var students = [];
var students = sheet2.getRange(2, 6, data).getValues();
//MailApp.sendEmail(students.toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
for (var i=0; i<students.length; i++){ // you are looping through rows and selecting the 1st and only column index
if (students[i][0] !== ''){
MailApp.sendEmail(students[i][0].toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
//MailApp.sendEmail(students[i][0].toString(), subject ,body, {from: from, attachments:[{fileName:"YourAttendaceRecord.xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
}
}
Explanation:
Based on your question, I understand the following steps:
Check if you have at least two unique subjects in column E. One way to do that is to find the unique list of subjects. If the length of that list is 2 or more it means that you have different subjects. In that case, the first block of the if statement evaluates to true and you add a yellow line in the row before the subject is changed.
If you have only one subject, namely the length of the unique list of subjects is 1 the first block of the if statement will evaluate to false. In that case, the script will check whether column A has 2 or more unique dates. If it does, the second block of the if statement will be executed and the script will add a yellow line in the row before the date is changed. Otherwise, it won't do anything.
Solution:
You can execute color() as a standalone script. I would advice you to save this function in a new .gs file and then simply call it within your current script. Namely, put color() anywhere you want in the code snippet you provided.
function color() {
const sss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = sss.getSheetByName("TempDataSet");
const subs = sheet.getRange('E2:E'+sheet.getLastRow()).getValues().flat();
const usubs = subs.filter((value, index, self)=>self.indexOf(value) === index);
const dts = sheet.getRange('A2:A'+sheet.getLastRow()).getDisplayValues().flat();
const udts = dts.filter((value, index, self)=>self.indexOf(value) === index);
if(usubs.length>1){
subs.forEach((s,i)=>{
if(i>1){
if(subs[i]!=subs[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
else if (udts.length>1){
dts.forEach((d,i)=>{
if(i>1){
if(dts[i]!=dts[i-1]){
sheet.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
}
Complete Solution:
function sendEmails(){
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = sss.getId();
var sheetName = sss.getName();
var sheet = sss.getSheetByName("TempDataSet");
var sheet1 = sss.insertSheet('TempDataSet_temp');
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
sheet.getDataRange().copyTo(sheet1.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
var shID = sheet1.getSheetId().toString();
sheet1.getRange(2, 1, sheet.getLastRow() -1, sheet.getLastColumn()).sort({column: 1, ascending: true});
var columns_delete = [7,2]; //[7,5,4,2];
columns_delete.forEach(col=>sheet1.deleteColumn(col));
SpreadsheetApp.flush();
const subs = sheet1.getRange('E2:E'+sheet1.getLastRow()).getValues().flat();
const usubs = subs.filter((value, index, self)=>self.indexOf(value) === index);
const dts = sheet1.getRange('A2:A'+sheet1.getLastRow()).getDisplayValues().flat();
const udts = dts.filter((value, index, self)=>self.indexOf(value) === index);
if(usubs.length>1){
subs.forEach((s,i)=>{
if(i>1){
if(subs[i]!=subs[i-1]){
sheet1.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
else if (udts.length>1){
dts.forEach((d,i)=>{
if(i>1){
if(dts[i]!=dts[i-1]){
sheet1.getRange(i+1,1,1,5).setBackground('yellow');
}}});
}
SpreadsheetApp.flush();
var from = Session.getActiveUser().getEmail();
var subject = 'Batch Attendance Record for Your Reference';
var body = 'Dear Student,'+ '\n\n' + 'Greetings! Please find the batch attendance record attached. Stay safe and blessed.' + '\n\n' + 'Thank you.';
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID+"&gid="+shID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
sss.deleteSheet(sss.getSheetByName('TempDataSet_temp'));
var sheet2 = sss.getSheetByName('StudentList');
var data = sheet2.getLastRow();
var students = [];
var students = sheet2.getRange(2, 6, data).getValues();
//MailApp.sendEmail(students.toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
for (var i=0; i<students.length; i++){ // you are looping through rows and selecting the 1st and only column index
if (students[i][0] !== ''){
MailApp.sendEmail(students[i][0].toString(), subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
//MailApp.sendEmail(students[i][0].toString(), subject ,body, {from: from, attachments:[{fileName:"YourAttendaceRecord.xlsx", content:contents, mimeType:"MICROSOFT_EXCEL"}]});
}
}
}

returning nested json values using loop (google spreadsheet)

I have this google spreadsheet script that pulls in json formatted book data. I have no problem displaying book title and author, but he "offerData" object can contain a different amount of elements (prices from sellers) depending on the book. Right now I created a loop and am storing the offerData values like so:
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
and am returning the data like this:
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
Obviously this only returns 3 sellers with price, condition, seller info. The issue is that a book doesn't always have 3 sellers, it can be anywhere from 1 to 10 or so.
My question is how can I return all offerData (price/condition/seller) here? :
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
--
function getBookDetails(isbn) {
// Query the book database by ISBN code.
if (isbn !== "") {
var url = "https://api.bol.com/catalog/v4/search/?apikey=myapi6&offers=all&format=json&q=" + isbn;
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response);
if (results.totalResultSize) {
// There'll be only 1 book per ISBN
var book = results.products[0];
// get Title and Authors
var title = (results.products[0]["title"]);
var specstag = (results.products[0]["specsTag"]);
var offerdata = results.products[0]["offerData"];
if (typeof offerdata.offers !== 'undefined' && offerdata.offers.length > 0) {
var arrayLength = offerdata.offers.length;
var price = [];
var condition = [];
var seller = [];
for (var i = 0; i < arrayLength; i++) {
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
}
}
}
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
return resultRow;
}
}
the answer
var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
resultRow[0][3*i+2]=price[i];
resultRow[0][3*i+3]=condition[i];
resultRow[0][3*i+4]=seller[i];
}
how you should think about it is to see the index of the elements in the array and then find relation between i and the index you want
var resultRow = [
[
title, //[0][0]
specstag, //[0][1]
price[0], //[0][2]
condition[0], //[0][3]
seller[0], //[0][4]
price[1], //[0][5]
condition[1], //[0][6]
seller[1], //[0][7]
price[2], //[0][8]
condition[2], //[0][9]
seller[2]//[0][10]
]
];
You might be looking for something like this;
var data = { title: null,
spcstag: null,
pcs: [],
};
offerData.offers.forEach( p => { var pcsData = {};
!!data.title || data.title = p.title;
!!data.specstag || data.specstag = p.specstag;
pcsData.price = p.price;
pcsData.condition = p.condition;
pcsData.seller = p.seller;
data.pcs.push(pcsData);
});

Categories