Object Keys from a JSON is saving the last value

1

People when I run Object Keys it captures every Array of the Object and updates the data of component only not all, and the output only comes with the last Array value:

var obj = {
  index: {
    path: "/",
    component: "./platform/system/index/index.vue",
    meta: {
      nav: "none"
    }
  },
  teste: {
    path: "/teste",
    component: "./platform/system/index/teste.vue",
    children: {
      userList: {
        path: "/users",
        component: "./platform/system/users/index.vue",
        lazy: "base"
      },
      testList: {
        path: "/system",
        component: "./platform/system/test/system.vue",
        lazy: "base"
      }
    }
  }
};

class Access {
  static getRaiz(obj) {
    var teste = {};

    Object.keys(obj).forEach(function(item) {
      var json = obj[item],
        directory = json.component;

      Object.assign(teste, json, {
        component: "() => import('" + directory + "')"
      });
    });
    return JSON.stringify(teste, null, '\t');
  }
}


document.body.innerHTML = '<pre>' + Access.getRaiz(obj) + '</pre>';
    
asked by anonymous 20.10.2017 / 22:46

1 answer

1

The problem is in the way Object.assign works. This method overrides all the properties in the object that already exist and adds all those that do not exist.

See a small example of this principle:

let pessoa1 = { nome: "Marco", idade : 20};

//atribuir nome e altura a pessoa1
Object.assign(pessoa1, { nome: "Serafim", altura: 1.8});

console.log(pessoa1);

Notice how nome was replaced and altura was added.

In your code when you run assign :

Object.assign(teste, json, {
    component: "() => import('" + directory + "')"
});

It will replace all existing properties with the same name, specifically path and component , so you only see the properties of the last property, teste .

If you want to create a new object with a modified component , you can simplify it to something like:

teste[item] = json;
teste[item].component = "() => import('" + directory + "')";

Example:

var obj = {
  index: {
    path: "/",
    component: "./platform/system/index/index.vue",
    meta: {
      nav: "none"
    }
  },
  teste: {
    path: "/teste",
    component: "./platform/system/index/teste.vue",
    children: {
      userList: {
        path: "/users",
        component: "./platform/system/users/index.vue",
        lazy: "base"
      },
      testList: {
        path: "/system",
        component: "./platform/system/test/system.vue",
        lazy: "base"
      }
    }
  }
};

class Access {
  static getRaiz(obj) {
    var teste = {};

    Object.keys(obj).forEach(function(item) {
      var json = obj[item],
        directory = json.component;
      
      teste[item] = json;
      teste[item].component = "() => import('" + directory + "')";

    });
    return JSON.stringify(teste, null, '\t');
  }
}


document.body.innerHTML = '<pre>' + Access.getRaiz(obj) + '</pre>';
    
20.10.2017 / 23:33