0

Here is the format which my code is generating:

[
    {
        "certifications": [
            {
                "certificate": "NA",
                "completed_on": "2019-09-24T18:30:00.000Z",
                "tc_name": "TC-174195"
            }
        ],
        "firstname": "Dipak",
        "lastname": "Das",
        "email": "dasdipak99@gmail.com"
    }
]

And I wanted to design like below format:

[
  {
    firstname: "Dipak",
    lastname: "Das",
    email: "dasdipak99@gmail.com",
    certifications: [
      {
        certificate: "NA",
        completed_on: "2019-09-24T18:30:00.000Z",
        tc_name: "TC-174195"
      }
    ]
  }
]

Below is my code :

var user = [];
var certificate = {
  certifications: []
};

certificate["firstname"] = rows[0].firstname;
certificate["lastname"] = rows[0].lastname;
certificate["email"] = rows[0].email;

for (let i = 0; i < rows.length; ++i) {
  certificate.certifications.push({
    certificate: rows[i].certification_names,
    completed_on: rows[i].completed_on,
    tc_name: rows[i].tc_name
  });
}

Any ideas how to maintain the insertion order? I am very new to javascript, apologies if i haven't explain well.

Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • 1
    Based on your description, it looks like it _is_maintaining the insertion order. Your object first has `certifications`, then `firstname`, `lastname`, and `email`, and that's the format you're supposedly getting. – JLRishe Jan 14 '20 at 04:44
  • Hi @JLRishe - Could you please guide me to maintain `firstname `, `lastname `, `email ` and `certifications ` ? –  Jan 14 '20 at 04:46
  • 1
    Seems like you just need to do what you're already doing, but insert `certifications` at the end instead of at the beginning. I'm also a bit curious what you're really trying to achieve here. Trying to maintain object properties in a specific order is a bit futile, and I wouldn't recommend relying on that for whatever it is you're trying to do. – JLRishe Jan 14 '20 at 04:48
  • https://stackoverflow.com/questions/9658690/is-there-a-way-to-sort-order-keys-in-javascript-objects – Matt Jan 14 '20 at 04:51
  • https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Matt Jan 14 '20 at 04:52
  • 2
    agree with @JLRishe. Not sure why you would need to maintain the order of an object which is something you shouldn't rely on. It would be a different case if it was an array. – ibex Jan 14 '20 at 04:52
  • So is it fine to keep `certifications`, then `firstname`, `lastname`, and `email` in this order? @JLRishe @ibex –  Jan 14 '20 at 04:56
  • javascript objects does not guarantee the order of insertion https://stackoverflow.com/a/30919039/6904782. – Nijeesh Joshy Jan 14 '20 at 04:59
  • 1
    @NijeeshJoshy JS does guarantee that for non-integer key names since 2015. Still not a good idea to rely on it though. – JLRishe Jan 14 '20 at 06:21

2 Answers2

1

Since ES6, there is a claim that the order would be

  1. first numbers in increasing numbers
  2. keys by insertion order

There is this blog post and this Stackoverflow thread.

But your lines of

var certificate = {
  certifications: []
};

made certifications the first property. So you would need:

var certificate = {};

certificate["firstname"] = "Albert";
certificate["lastname"] = "Lee";
certificate["email"] = "a@b.com";
certificate["certifications"] = [];

certificate.certifications.push({
  certificate: "Java",
  completed_on: "2020/01/02",
  tc_name: "java2020"
});

console.log(certificate);

To better guarantee an order, use Map, to keep the original insertion order of the keys. Usually you may not need it, but only for some reason if you want the order, and can have such order in a for-of loop:

var certificate = new Map();

certificate.set('firstname', "Albert");
certificate.set('lastname', "Lee");
certificate.set('email', "a@b.com");
certificate.set("certifications", []);
certificate.get("certifications").push({
  "certificate": "Java",
  "completed_on": "2020/01/02",
  "tc_name": "java2020"
})

console.log(certificate);

for (e of certificate) console.log(e)

StackOverflow won't print anything for:

console.log(certificate);

using Node or Chrome, it is:

Map {
  'firstname' => 'Albert',
  'lastname' => 'Lee',
  'email' => 'a@b.com',
  'certifications' => [
    {
      certificate: 'Java',
      completed_on: '2020/01/02',
      tc_name: 'java2010'
    }
  ]
}
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
0

Initialize the empty certifications array after the firstname, lastname, and email:

let rows=[{certification_name:"NA",completed_on:"2019-09-24T18:30:00.000Z",tc_name:"TC-174195"}]

let certificate = {}

certificate["firstname"] = "Dipak"
certificate["lastname"] = "Das"
certificate["email"] = "dasdipak99@gmail.com"
certificate["certifications"] = []
for (let i = 0; i < rows.length; ++i) {
    certificate.certifications.push({
        "certificate": rows[i].certification_names,
        "completed_on": rows[i].completed_on,
        "tc_name": rows[i].tc_name
  })
}

console.log(certificate)
symlink
  • 11,984
  • 7
  • 29
  • 50
  • Insertion order is still not guaranteed because the standard does not mandate it. For the longest time Firefox refused to implement insertion order because not having insertion order was valid according to the spec but users managed to goad FF developers to do it. Note that any js engine may break this again in the future and the ES standards committee has refused to include it in the standard. **Do not** depend on object insertion order! Use other data structures if you want an ordered list – slebetman Jan 14 '20 at 06:48
  • This misguided interpretation of "order" for an unordered data structure is so bad that the maintainers of the `go` programming language added a random number generator so that their map/hash data structure will always have random order - they consider the minor slowdown of the random number generator to be worth teaching naive programmers a valuable lesson and I agree – slebetman Jan 14 '20 at 06:50
  • @slebetman I tested this on all the major browsers and it works just fine. – symlink Jan 14 '20 at 06:55
  • Yes but you still should not do it. It is not part of the javascript language - it is implementation detail. Never depend on implementation detail because it can change any time for any reason eg. if they change the structure of objects for speed optimizations. If that happens I know a lot of developers would consider the code that breaks as buggy instead of the browser – slebetman Jan 14 '20 at 06:58