Home > Net >  Get array length and push into each object
Get array length and push into each object

Time:06-28

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:

{
  "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.

CodePudding user response:

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);

CodePudding user response:

You can use Array.prototype.reduce() combined with Array.prototype.forEach():

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.reduce((a, { url, ids }) => {
  ids.forEach(id => {
    a[id] = a[id] || { length: 0, urls: [] }
    a[id].length  = 1
    a[id].urls.push(url)
  })
  return a
}, {})

console.log(output)

  • Related