尝试找到一种简单的方法来遍历对象结构,以构建queryString以传递给我的API端点。
场景 - 如果id
为空,请使用codes
或sku
或codes and sku
为空,则使用id
,而不是使用多个if()
1}}做这个条件是否有更好的方法来实现这一目标?如果全部存在,则应默认使用sku
var loopThrough = {
"OrderLine": [{
"Product": {
"Id": null,
"Codes": ["1112"],
"Sku": "CS1112"
},
"TotalValue": 0,
"Quantity": 1
}, {
"Product": {
"Id": null,
"Codes": ["1113"],
"Sku": "CS1113"
},
"TotalValue": 0,
"Quantity": 1
}],
"OriginatingSite": {
"Id": 1
},
"TotalValue": 0
};
var allIds = '?';
var first = true;
for (var i = 0; i < loopThrough.OrderLine.length; i++) {
var orderLines = loopThrough.OrderLine[i];
var prodId = orderLines.Product.Id;
var prodCodes = orderLines.Product.Codes;
var prodSku = orderLines.Product.Sku;
if (first) {
first = false;
if (prodId === null) {
allIds = allIds + "&code=" + orderLines.Product.Codes[0];
} else {
allIds = allIds + "&id=" + orderLines.Product.Id;
}
} else {
if (prodId !== null) {
allIds = allIds + "&id=" + orderLines.Product.Id
} else {
allIds = allIds + "&sku=" + orderLines.Product.Sku;
}
}
console.log(allIds)
}
&#13;
答案 0 :(得分:0)
没有太多可以改变的东西,任何更复杂的东西都会毁了整个观点。但你可以更加宽松&#39;在你的条件上,如果他们是自己的优先事项。
var loopThrough = {
"OrderLine": [{
"Product": {
"Id": null,
"Codes": ["1112"],
"Sku": "CS1112"
},
"TotalValue": 0,
"Quantity": 1
}, {
"Product": {
"Id": null,
"Codes": ["1113"],
"Sku": "CS1113"
},
"TotalValue": 0,
"Quantity": 1
}],
"OriginatingSite": {
"Id": 1
},
"TotalValue": 0
};
var allIdsArr = [];
var first = true;
for (var i = 0; i < loopThrough.OrderLine.length; i++) {
var orderLines = loopThrough.OrderLine[i];
var prodId = orderLines.Product.Id;
var prodCodes = orderLines.Product.Codes;
var prodSku = orderLines.Product.Sku;
allIdsArr.push(
prodId !== null ? 'id=' + prodId :
prodCodes !== null ? 'code=' + prodCodes :
'sku=' + prodSku
)
}
console.log('?' + allIdsArr.join('&'))
&#13;
答案 1 :(得分:0)
for
循环,使用map
简短版本可能是:
const loopThrough = {
"OrderLine": [{
"Product": {
"Id": null,
"Codes": ["1112"],
"Sku": "CS1112"
},
"TotalValue": 0,
"Quantity": 1
}, {
"Product": {
"Id": null,
"Codes": ["1113"],
"Sku": "CS1113"
},
"TotalValue": 0,
"Quantity": 1
}],
"OriginatingSite": {
"Id": 1
},
"TotalValue": 0
};
const url = "?" +
loopThrough.OrderLine
.map((order, index) => {
const product = order.Product;
return product.Id?
`id=${product.Id}`:
index === 0?
`sku=${product.Sku}`:
`code=${product.Codes[0]}`;
})
.join("&");
console.log(url);
&#13;