gpt4 book ai didi

javascript - 如何从 Google 表格中的列值分配对象?

转载 作者:行者123 更新时间:2023-12-01 23:59:33 24 4
gpt4 key购买 nike

我有一个 google 表格,其中一列包含一些数据。如何将这些值分配给新对象,例如 {'value[0]':value[0], 'value[1]':value[1],..., 'value[i]':value[我]}?

我写了这个脚本,但它仅从 names 的最后一个值分配对:

function getIngredientsList() {
const url = "SPREADSHEET_URL";
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName('Base');
const names = ws.getRange(2, 3, ws.getLastRow() - 1).getValues().map(a => a[0]);
let nameList;
for (let i = 0; i < names.length; i++){
if (names[i] !== ""){
let name = {[names[i]]:names[i]};
nameList = Object.assign(name);
}
}
return nameList;
}

我哪里错了,如何改正?

最佳答案

我相信你的目标如下。

  • 您想从单元格“C2:C28”中检索值,并希望创建一个键和值相同的对象。

为此,这个修改怎么样? Object.assign() 的参数是 Object.assign(target, ...sources)。所以在你的脚本中,let nameList = {}nameList需要像nameList = Object.assign(nameList, name)一样使用。

来自:

let nameList;
for (let i = 0; i < names.length; i++){
if (names[i] !== ""){
let name = {[names[i]]:names[i]};
nameList = Object.assign(name);
}
}

收件人:

let nameList = {};  // Modified
for (let i = 0; i < names.length; i++){
if (names[i] !== ""){
let name = {[names[i]]:names[i]};
nameList = Object.assign(nameList, name); // Modified
}
}

或者,与其他模式一样,当使用reduce 时,以下脚本也可以返回与上述修改后的脚本相同的值。

const nameList = ws.getRange(2, 3, ws.getLastRow() - 1).getValues()
.reduce((o, [e]) => {
if (e != "") Object.assign(o, {[e]: e});
return o;
}, {});

引用:

关于javascript - 如何从 Google 表格中的列值分配对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62099062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com