Add a non-existent item to a JSON from js

0

I've tried with:

var data = {};
var file = {file:{name: 'Getter - Blood.mp3', path: '/user1'}};
data.push(file);
//Y tambien asi
data.file = file;

But nothing works, no error or anything, but when you print it on the screen, the new items do not appear

    
asked by Hector Seguro 23.06.2016 в 19:40
source

2 answers

2

solution with array

If your intention is to have several records like "file" (from your example) you can start with an array

var data = [];
var file = {name: 'Getter - Blood.mp3', path: '/user1'};
data.push(file);
console.log(data);
// se muestra: 
// [ { name: 'Getter - Blood.mp3', path: '/user1' } ]
data.push({name: "Other.mp3", path: undefined});
console.log(data);
// se muestra:
// [ { name: 'Getter - Blood.mp3', path: '/user1' },
//  { name: 'Other.mp3', path: undefined } ]

solution with object

var data = {};
var file = {name: 'Getter - Blood.mp3', path: '/user1'};
data.file1 = file;
console.log(data);
// se muestra: 
// { file1: { name: 'Getter - Blood.mp3', path: '/user1' } }
data.file2 = {name: "Other.mp3", path: undefined});
console.log(data);
// se muestra:
// { file1: { name: 'Getter - Blood.mp3', path: '/user1' },
//   file2: { name: 'Other.mp3', path: undefined } }
    
answered by 28.06.2016 в 02:47
0

Before

fs.readdir(dir, function(err, files) {
    files.forEach(function(file) {
        if(fs.statSync(dir + '/' + file).isFile()){
            data.files = file; 
        }else{
            data.dirs = {file};
        }
    });
});
console.log(data);
res.render('algo', data);

After

//Lee todo de una carpeta sean archivos o directorios
fs.readdir(dir, function(err, files) {
    //Para por cada uno. 
    files.forEach(function(file) {
        console.log(file);
        //Pregunta: ¿Eres un archivo?
        if(fs.statSync(dir + '/' + file).isFile()){
            //Aqui si los es, entonces lo agrega a la variable archivos
            data['files'] = file; 
        }else{
             //Aqui NO los es, entonces lo agrega a la variable directorios
             data['dirs'] = file; 
        } 
    });
    //Lo envia
    res.render("algo", data);
    //Imprime todos los datos
    console.log(data);
}); 

You can also use fs.readdirSync ()

var files = fs.readdirSync(_dir);
//lo mismo excepto por el callback
    
answered by 23.06.2016 в 20:18