javascript - How to count multiple objects inside nested array sequentially in react js - Stack Overflow

I have an array structure like this :const array = [[{"item": { "name": "item

I have an array structure like this :

const array = [
    [
        {
            "item": { "name": "item1" },
            "property": { "name": "property1" }
        },
        {
            "item": { "name": "item2" },
            "property": { "name": "property2" }
        }
    ],
    [
        {
            "item": { "name": "item3" },
            "property": { "name": "property3" }
        }
    ]
]

If I run this mand in pure Javascript:

let count = 0
for(let i = 0; i < array.length; i++) {
    for(let j = 0; j < array[i].length; j++) {
        count ++
        console.log(count)
    }
}

Then the output will be like this :

1,2,3

I want to be able to generate the output like above using array.map() in ReactJS and keep those sections. This is the code I'm currently using:

return (
    <div className="container">
    {array.map((nestedArray, arrayIndex) => (
        <div key={arrayIndex} className="array-list">
            <h1>Group: {arrayIndex+1}</h1>
            {nestedArray.map((items, nestedArrayIndex) => (
                <p>Item: {nestedArrayIndex+1}</p>
            ))}
        </div>
    ))}
    </div>
)

And this is the render output (using my css styles):

What is an effective and short way to do it?

I hope I have explained everything clearly

I have an array structure like this :

const array = [
    [
        {
            "item": { "name": "item1" },
            "property": { "name": "property1" }
        },
        {
            "item": { "name": "item2" },
            "property": { "name": "property2" }
        }
    ],
    [
        {
            "item": { "name": "item3" },
            "property": { "name": "property3" }
        }
    ]
]

If I run this mand in pure Javascript:

let count = 0
for(let i = 0; i < array.length; i++) {
    for(let j = 0; j < array[i].length; j++) {
        count ++
        console.log(count)
    }
}

Then the output will be like this :

1,2,3

I want to be able to generate the output like above using array.map() in ReactJS and keep those sections. This is the code I'm currently using:

return (
    <div className="container">
    {array.map((nestedArray, arrayIndex) => (
        <div key={arrayIndex} className="array-list">
            <h1>Group: {arrayIndex+1}</h1>
            {nestedArray.map((items, nestedArrayIndex) => (
                <p>Item: {nestedArrayIndex+1}</p>
            ))}
        </div>
    ))}
    </div>
)

And this is the render output (using my css styles):

What is an effective and short way to do it?

I hope I have explained everything clearly

Share Improve this question edited Aug 7, 2021 at 6:44 stu asked Aug 7, 2021 at 5:40 stustu 491 silver badge7 bronze badges 1
  • FYI: This happens because of key attribute on the div. If you remove the key then it will show as you want it to but React will throw an error. – Ayush Gupta Commented Aug 7, 2021 at 5:58
Add a ment  | 

3 Answers 3

Reset to default 5

If you want to keep those sections I think the easiest thing would be to use a variable to keep track of the count. You can then use map to iterate over array and its arrays, updating count as each new array is encountered.

To do that you should separate out the code into a function that you call from your ponent's return.

const array=[[{item:{name:"item1"},property:{name:"property1"}},{item:{name:"item2"},property:{name:"property2"}}],[{item:{name:"item3"},property:{name:"property3"}}]];

function Example({ data }) {

  function createJSX(data) {

    let count = 0;

    return array.map((arr, i) => {
      return (
        <div>
          <h3>Group: {i + 1}</h3>
          {arr.map(obj => {
            ++count;
            return <p>Item: {count}</p>;
          })}
        </div>
      )
    });

  }

  return (
    <div>
      {createJSX()}
    </div>
  );

};

// Render it
ReactDOM.render(
  <Example data={array} />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare./ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare./ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>

And then call the function from your render:

return (
  <div className="container">
    {createJSX()}
  </div>
);

You could do something like this.

const array = [
  [
    {
      item: { name: "item1" },
      property: { name: "property1" }
    },
    {
      item: { name: "item2" },
      property: { name: "property2" }
    }
  ],
  [
    {
      item: { name: "item3" },
      property: { name: "property3" }
    }
  ]
];

 <div className="container">
    {array.flat().map((item, arrayIndex) => (
       <p>Item: {arrayIndex + 1}</p>
    ))}
 </div>

You will need to flatten your array first, then all children will be in one array.

Another option if you want to keep track of those sections:

render() {
  let indexCount = 0;
  return (
    <div className="container">
      {array.map((nestedArray, arrayIndex) => (
        <div key={arrayIndex} className="array-list">
          {nestedArray.map((items, nestedArrayIndex) => (
            <p key={(indexCount += 1)}>Item: {indexCount}</p>
          ))}
      </div>
    ))}
  </div>
);

}

You will need a variable to save the current indexCount then just simply increase it each time you render the final index. Also, I added a missing key to your child nestedArray render.

Just a side note is that it's not remended to use array indexes as render list keys.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745170373a4614889.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信