Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get array length and push into each object

I have a function

const output = {}
sites.forEach(obj=>{
    const ids = obj.ids
    if(ids && ids.length>0){
        ids.forEach(id=>{
            if(!output[id]){
                output[id] = []
            }
            output[id].push(obj.url);
        });
    }
});

fs.writeFileSync('cleanedData.json', JSON.stringify(output));

that takes data such as:

{ 
     url: "www.site.com", 
     ids: ["F20", "C10", "C05"] 
}, 
{ 
    url: "www.site.com/something", 
    ids: ["F20", "C05", "C10"] 
}, 
{ 
    url: "www.site.com/somethingelse", 
    ids: ["F20", "C12", "C05"] 
}

and transforms it so that I have a list of all ids and all urls with that id:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "F20": [
    "www.site.com",
    "www.site.com/something",
    "www.site.com/somethingelse"
  ]
}, {
  "C10": [
    "www.site.com",
    "www.site.com/something"
  ]
}, {
  "C12": [
    "www.site.com/somethingelse"
  ]
}, {
  "C05": [
    "www.site.com",
    "www.site.com/something",
    "www.site.com/somethingelse"
  ]
}

I’m able to get a count of each id’s array length with

console.log(Object.values(output).map(id => id.length))

But can’t figure out how to include that as part of the forEach, so that I have a key/value in each object that shows the length of the array.

>Solution :

Use nested objects in the output, and give it a length property that you increment when you push onto the array.

const sites = [{
    url: "www.site.com",
    ids: ["F20", "C10", "C05"]
  },
  {
    url: "www.site.com/something",
    ids: ["F20", "C05", "C10"]
  },
  {
    url: "www.site.com/somethingelse",
    ids: ["F20", "C12", "C05"]
  }
];

const output = {};
sites.forEach(obj => {
  const ids = obj.ids
  if (ids && ids.length > 0) {
    ids.forEach(id => {
      if (!output[id]) {
        output[id] = {length: 0, urls: []}
      }
      output[id].urls.push(obj.url);
      output[id].length++;
    });
  }
});

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading