Search code examples
javascriptjsonjavascript-objects

How to convert a javascript object array file to customized json file


I'm getting a javascript object array. I'm trying to write it to json file by replacing certain params. i don't require comma separated between every object and need to insert a new json object before every existing object. current js object is

[{name:"abc", age:22},
 {name:"xyz", age:32,
 {name:"lmn", age:23}]

the expected json output file is,

{"index":{}}
{name:"abc", age:22}
{"index":{}}
{name:"xyz", age:32}
{"index":{}}
{name:"lmn", age:23}

My code is

sourceData = data.map((key) => key['_source'])
const strData = JSON.stringify(sourceData);
const newStr = strData.replace("},{", "}\n{");
const newStr2 = newStr.replace(`{"name"`, `{"index" : {}}\n{"name"`);
fs.writeFile('data.json', newStr2, (err) => {
    if (err) {
        throw err;
    }
    console.log("JSON data is saved.");
});

But in my output only the first object is changing. I need this to happen my entire output json file. Please help. Thanks


Solution

  • I'd insert dummy objects first and then map stringify over the result:

    array = [
        {name: "abc", age: 22},
        {name: "xyz", age: 32},
        {name: "lmn", age: 23}]
    
    
    result = array
        .flatMap(item => [{index: {}}, item])
        .map(x => JSON.stringify(x))
        .join('\n')
    
    console.log(result)
    
    // fs.writeFileSync('path/to/file', result)