0

I would like to know how to assign the object as shown. I have objects fields and fields1, if object value is empty,list at the end

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: ""
}

miyavv
  • 763
  • 3
  • 12
  • 30
  • 1
    You should rethink your structure. Make fields an array and only pass non-null values into it by using validation, either client or server-side. – Rob Apr 21 '20 at 10:43
  • You want to move all valid value into head of object and empty value will move to the bottom, right? – Hoàng Minh Thông Apr 21 '20 at 10:45
  • @HoàngMinhThông yes – miyavv Apr 21 '20 at 10:47
  • 2
    JavaScript gives you no guarantee that your object properties are listed in a specific order. Even though all major implementations do that, it's basically just a co-incidence you should not rely upon. If you need to make sure that your values are in a certain order, I'd follow @Alex's suggestion of using an array. – fjc Apr 21 '20 at 10:51
  • keys in object does not follow order, If you need order better use array – Varun Sukheja Apr 21 '20 at 10:52

1 Answers1

0

If the fields are actually named f1, f2, f3, f4 then that determines the order and you could look at each field of the current object and promote any non-empty values to the next non-empty field in the resulting object like this:

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));
Always Learning
  • 5,510
  • 2
  • 17
  • 34