gpt4 book ai didi

javascript - 在数组的开头添加键值

转载 作者:行者123 更新时间:2023-11-29 17:19:45 25 4
gpt4 key购买 nike

我想在 javascript JSON 数组的开头添加一个键->值对,如下所示:

var temp = new Array();
temp = {
['LABEL_ID': 10, 'LABEL_TYPE': A3],
['LABEL_ID': 17, 'LABEL_TYPE': A6]
}

我想做什么:

var temp = new Array();
temp = {
'PAPER': A80
['LABEL_ID': 10, 'LABEL_TYPE': A3],
['LABEL_ID': 17, 'LABEL_TYPE': A6]
}

你能帮帮我吗?

编辑这是我的代码:

// returns paper type from selected grid line
var ppt = Ext.getCmp('labelType').getValue();

// returns selected grid rows
var rows = Ext.getCmp('labelGrids').getSelectionModel().getSelection();


// here is my array that I want to add ppt variable value to existing array, then I will convert this to a JSON array
for (var i = 0; i < count; i++)
{
prints[i] = {'LABEL_ID': rows[i].data.LABEL_ID, 'LABEL_TYPE':rows[i].data.LABEL_TYPE}
}

原因是在数组的开头添加ppt值,我只需要在服务器端记录这条记录。因此,我不想在所有行中重复!

最佳答案

好吧,我希望你在问题中指的是这个脚本:

要回答您编辑过的问题,一种简单的方法是将其包装在另一个对象中:

var temp = new Array();
temp = [
{"LABEL_ID": 10, "LABEL_TYPE": "A3"},
{"LABEL_ID": 17, "LABEL_TYPE": "A6"}
]
// wrap temp in another object;

var obj = {};
obj.PAPER = A80;
obj.Data = temp;
//And convert to json.
console.log(JSON.stingify(obj));

输出:

{"PAPER":"A80","Data":[{"LABEL_ID":10,"LABEL_TYPE":"A3"},{"LABEL_ID":17,"LABEL_TYPE":"A6"}]}

希望这对您有所帮助。调用该函数将为您的对象添加所需的属性

var temp = new Array();
temp = [
{"LABEL_ID": 10, "LABEL_TYPE": "A3"},
{"LABEL_ID": 17, "LABEL_TYPE": "A6"}
]

addPaperProperty(temp, 'PAPER', ['AA','BB']);

function addPaperProperty(currentArray, newPropertyField, newPropertyArr){
var newArray = [];
var i=0;
$(temp).each(function(){
this[newPropertyField] = newPropertyArr[i++];
newArray.push(this);
});
console.log(newArray);
return newArray;
}

结果会是

[{LABEL_ID: 10, LABEL_TYPE: "A3", PAPER: "AA"},
{LABEL_ID: 17, LABEL_TYPE: "A6", PAPER: "BB"}]

关于javascript - 在数组的开头添加键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13840946/

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