Home > Net >  Building an array instead of hardcoding it
Building an array instead of hardcoding it

Time:12-15

How do I make a loop that will create the INITIAL_MAP array instead of hardcoding it?

const INITIAL_MTL = new THREE.MeshPhongMaterial({ color: 0xC0C0C0, shininess: 10 });

const INITIAL_MAP = [
{ childID: "part-001", mtl: INITIAL_MTL },
{ childID: "part-002", mtl: INITIAL_MTL },
{ childID: "part-003", mtl: INITIAL_MTL },
{ childID: "part-004", mtl: INITIAL_MTL },
{ childID: "part-005", mtl: INITIAL_MTL },
{ childID: "part-006", mtl: INITIAL_MTL },
{ childID: "part-007", mtl: INITIAL_MTL },
{ childID: "part-008", mtl: INITIAL_MTL },
{ childID: "part-009", mtl: INITIAL_MTL },
{ childID: "part-010", mtl: INITIAL_MTL },
];

CodePudding user response:

Using the for loop to push to the array

const INITIAL_MTL = new THREE.MeshPhongMaterial({ color: 0xC0C0C0, shininess: 10 });

const INITIAL_MAP = []
for (let i=1; i<=10;i  ) INITIAL_MAP.push({
    childID: `part-${String(i).padStart(3, '0')}`, // padding the number
    mtl: INITIAL_MTL // storing the object from above
  })

console.log(INITIAL_MAP)
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js" integrity="sha512-dLxUelApnYxpLt6K2iomGngnHO83iUvZytA3YjDUCjT0HDOHKXnVYdf3hU4JjM8uEhxf9nD1/ey98U3t2vZ0qQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Here is another way using Array.from to get an array to map

const INITIAL_MTL = new THREE.MeshPhongMaterial({ color: 0xC0C0C0, shininess: 10 });

const INITIAL_MAP = Array
  .from({ length: 10 }) // create an array with 10 elements
  .map((_, i) => ({     // the i goes from 0-9
    childID: `part-${String(i 1).padStart(3, '0')}`, // padding the number 1
    mtl: INITIAL_MTL    // storing the object from above
  }))

console.log(INITIAL_MAP)
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js" integrity="sha512-dLxUelApnYxpLt6K2iomGngnHO83iUvZytA3YjDUCjT0HDOHKXnVYdf3hU4JjM8uEhxf9nD1/ey98U3t2vZ0qQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

UPDATE with your part color

const PART_COLOR = [true, false, true, false, false, false, true, false, false, false];
const INITIAL_MAP = []
for (let i = 1; i <= parts; i  ) INITIAL_MAP.push(
  { childID: `part-${String(i).padStart(3, '0')}`, // padding the number 
    mtl: PART_COLOR[i] ? INITIAL_MTL : ARICON_COLOR })
}
  • Related