0

I am having a heck of a time trying to assign derived schema to an object. I think you'll get what I'm trying to do. It should not be this difficult. What am I doing wrong?

let defaultValues = { 'apid': 1234, 'app': 'test' };
let hostFields = [
    {
        "name": "FirstName",
        "required": true,
        "label": {
            "singular": "First Name"
        }
    },
    {
        "name": "LastName",
        "required": false,
        "label": {
            "singular": "Last Name"
        }
    }
];
let appFields = ['FirstName', 'LastName', 'Bogus'];
let saveAll = [];

for (let i=0; i<hostFields.length; i++) {
    let f = hostFields[i];
    let save = defaultValues;

    save.requiredByHost = 0;
    save.requiredByApp = 0;

    if (f.required === true) {
        save.requiredByHost = 1;
    }

    if (appFields.indexOf(f.name) !== -1) {
        save.requiredByApp = 1;
    }

    if (save.requiredByHost === 1 || save.requiredByApp === 1) {
        save.schema = f;
        saveAll.push(save);
    }
});

console.log(saveAll);
  • Assignment does not copy the `defaultValues`, you always refer to the same object. – Bergi Oct 03 '16 at 20:56
  • 1
    Pretend for a moment that we cannot see your screen. What error are you getting? What line? How is your code not working as expected? –  Oct 03 '16 at 20:56
  • Put the object literal with the default values inside the loop so that you get a new instance on every iteration, or manually copy all properties every time. – Bergi Oct 03 '16 at 20:58
  • I did this `let save = JSON.parse(JSON.stringify(defaultValues));` and it seemed to fix. – user3287495 Oct 03 '16 at 21:11
  • See http://felix-kling.de/jsbasics/#/10 for how objects work. – Felix Kling Oct 03 '16 at 21:19

0 Answers0