Home > Software engineering >  How to slice or limit dynamic nested array nodejs
How to slice or limit dynamic nested array nodejs

Time:12-20

How to slice data in nested array? I want to use it with pagination for limit the data for display. I have try it with object key but only limit the nested array without show parent data

I am trying use object key like this. The ouput is correct but not show the parent like data1, data2, etc

  dataJson.map(d => {
    for(var i=0;i<Object.keys(d).length;i  ){
      let rev = d[Object.keys(d)].slice(1 * 2 - 2, 1 * 2);
      console.log(rev);
   }
  })

output

    {
      id: 1,
      name: "John" 
    },
    {
      id: 2,
      name: "James" 
    }

    {
      id: 1,
      name: "May" 
    },
    {
      id: 2,
      name: "Joe" 
    }

structure data json in single object array

 "data": [
    {
      "data 1": [
        {
          id: 1,
          name: "John" 
        },
        {
          id: 2,
          name: "James" 
        },
        {
          id: 3,
          name: "James" 
        }
      ]
    },
    {
      "data 2": [
        {
          id: 1,
          name: "May" 
        },
        {
          id: 2,
          name: "Joe" 
        },
        {
          id: 3,
          name: "Din" 
        }
      ]
    },
    data 3,
    many data others
 ]

i want to display it like this (limit data and show 2 data from nested array) with function slice

 "data": [
    {
      "data 1": [
        {
          id: 1,
          name: "John" 
        },
        {
          id: 2,
          name: "James" 
        }
      ]
    },
    {
      "data 2": [
        {
          id: 1,
          name: "May" 
        },
        {
          id: 2,
          name: "Joe" 
        }
      ]
    },
 ]

CodePudding user response:

This is your requirement

    var array = [];
var data = []
var data1 = [{ name: 's' }, { name: 'v' }, { name: 'c' }];
var data2 = [{ name: 's' }, { name: 'v' }, { name: 'c' }];

array['data'] = data;
data['data 1'] = data1;
data['data 2'] = data2;

for (var i = 1; i < 3; i  ) {
    array.data['data '   i].splice(2, 1)

}
console.log(array);

OutPut:

[
  data: [
    'data 1': [ [Object], [Object] ],
    'data 2': [ [Object], [Object] ]
  ]
]

CodePudding user response:

See more about Object.entries

let data = [{ "data 1": [{ id: 1, name: "John" }, { id: 2, name: "James" }, { id: 3, name: "James" }] }, { "data 2": [{ id: 1, name: "May" }, { id: 2, name: "Joe" }, { id: 3, name: "Din" }] },]
let out = data.map(v => {
    let obj = {}
    for (let [k, arr] of Object.entries(v))
        obj[k] = arr.slice(0, 2);

    return obj
});
console.log(out);

  • Related