gpt4 book ai didi

javascript - 更有效的字符串创建方式

转载 作者:搜寻专家 更新时间:2023-10-31 23:47:39 24 4
gpt4 key购买 nike

我有以下对象并需要这个字符串:

product_name,@dummy1,@dummy2,seller_sku,@price,item_quantity,@dummy6,@dummy7,@dummy8,@dummy9,@dummy10,@dummy11,@dummy12,@dummy13,@dummy14,@dummy15,@dummy16,@dummy17,@dummy18,@dummy19,@dummy20,@dummy21,@dummy22,@dummy23,@dummy24,@dummy25,fulfillment_channel

{ 
countFields: 27,
fields:
{ product_name: 0,
seller_sku: 3,
price: 4,
item_quantity: 5,
fulfillment_channel: 26
}
}

对象和字符串(包括长度)可能会发生变化。

我这样创建字符串(使用 lodash):

function tableString(fields){
var obj = _.invert(fields.fields);
obj.length = fields.countFields;
var values = Array.prototype.slice.apply( obj );
var arr = _.merge(new Array(fields.countFields),values).map(function(val,i){
if (val == 'price' || !~values.indexOf(val)) {
if (val == 'price') {
return '@price';
}
return '@dummy' + i;
}
return val;
});

return arr.join(',');
}

var first = {
countFields: 27,
fields: {
product_name: 0,
seller_sku: 3,
price: 4,
item_quantity: 5,
fulfillment_channel: 26
}
}

console.log(tableString(first));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>

我想避免在末尾使用 map()/array 函数。有人找到一种更简单的方法来从对象创建上面的字符串吗?

最佳答案

我不知道这是否更容易,但你会在末尾得到一个字符串和它的普通 javascript。

function tableString(fields){
var reversedFields = {};
for(var key in fields.fields){ // we swapped key and value
reversedFields[fields.fields[key]] = key;
}

for(var i=0,x=fields.countFields-1,result = "";i<fields.countFields;i++){
if(reversedFields[i]){
result += (reversedFields[i] == 'price' ? '@price' : reversedFields[i]);
} else {
result += '@dummy' + i;
}
if(i < x){
result += ",";
}
}

return result;
}

var res = tableString({
countFields: 27,
fields:{
product_name: 0,
seller_sku: 3,
price: 4,
item_quantity: 5,
fulfillment_channel: 26
}
});

// result product_name,@dummy1,@dummy2,seller_sku,@price,item_quantity,@dummy6,@dummy7,@dummy8,@dummy9,@dummy10,@dummy11,@dummy12,@dummy13,@dummy14,@dummy15,@dummy16,@dummy17,@dummy18,@dummy19,@dummy20,@dummy21,@dummy22,@dummy23,@dummy24,@dummy25,fulfillment_channel

关于javascript - 更有效的字符串创建方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32239658/

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