我有JSON对象和数组
sampleJson={"id":1,"option1":"","option2":"","option3":""}
sampleArray=["car","","Animals"]
我想以下列格式将sampleArray添加到sampleJson
sampleJson={"id":1,"option1"="car","option2":"Animals","option3":""}
示例数组将随机化,如["","car",""] Or ["","animal","Car"]?
答案 0 :(得分:0)
var sampleJson={"id":1,"option1":"","option2":"","option3":""}
var sampleArray=["car","","Animals"];
var count = 1;
sampleArray.forEach(function(ele){
if(ele.length){
sampleJson['option' + count] = ele;
count++;
}
})
console.log(sampleJson);//{id: 1, option1: "car", option2: "Animals", option3: ""}
答案 1 :(得分:0)
var sampleJson={"id":1,"option1":"","option2":"","option3":""}
var sampleArray=["car","","Animals"]
Object.keys(sampleJson).filter(function(k) {
return k.includes('option');
}).forEach(function(k,i) {
if (sampleArray.length > i)
sampleJson[k] = sampleArray[i];
});
console.log(sampleJson)
希望它有所帮助!!
答案 2 :(得分:0)
感谢您的帮助,我找到了解决方案
var i=1;
sampleData.forEach(element => {
if(element.length != 0){
sampleJson['option'+i]=element;
i++;
}
});