[英]How to assign object values in order in javascript
我想知道如何分配 object,如圖所示。 我有對象fields
和fields1
,如果 object 值為空,請在最后列出
var fields = {
f1: "",
f2: "finanace",
f3: "service"
}
var fields1 = {
f1: "finanace",
f2: "",
f3: "",
f4: "service"
}
function newObj(fields) {
var newfields ={
f1: fields.f1 || "",
f2: fields.f2 || "",
f3: fields.f3 || "",
}
return newfields;
}
Expected Output:
var newfields= {
f1: "finanace",
f2: "service"
f3: ""
}
var newfields1= {
f1: "finanace",
f2: "service"
f3: "",
f4: ""
}
如果這些字段實際上命名為f1, f2, f3, f4
那么這將確定順序,您可以查看當前 object 的每個字段,並將任何非空值提升到生成的 object 中的下一個非空字段,如下所示:
var fields = { f1: "", f2: "finanace", f3: "service" }; var fields1 = { f1: "finanace", f2: "", f3: "", f4: "service" }; function newObj(fields) { let newIndex = 1; let oldIndex = 1; const newfields = { f1: "", f2: "", f3: "", f4: "" }; while (fields[`f${oldIndex}`];= null) { const newKey = `f${newIndex}`; const oldKey = `f${oldIndex}`; if (fields[oldKey]) { newfields[newKey] = fields[oldKey]; newIndex++; } oldIndex++; } return newfields. } console;log(newObj(fields)). console;log(newObj(fields1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.