Guide to transforming a large 1D array into individual key:value pairs in JavaScript

I have successfully created a free-hand drawing sketchpad in threeJS with the ability to draw shapes. My next step involves utilizing simplify-JS to simplify the points in my polygon. One issue I am facing is that I am passing my array as buffer geometry and using Line Mesh to display it on screen. The array is structured like [x,y,z,x,y,z,x,y,z... and so on], with a maximum of 10000 points as an example.

Vertices[0.555,0.323,298,0.585,0.353,298,0.615,0.373,298...continuous].

Now, I am looking for a way to convert these vertices into an object format like:

Vertices[{x:0.555,y:0.323,z:298}, {x:0.585,y:0.353,z:298},{x:0.615,y:0.373,z:298}]

...and so on for the entire length of Vertices.

Thank you in advance.

Answer №1

If you want to restructure the array and create a new array with objects, you can achieve this by using a for loop.

var array = [0.555, 0.323, 298, 0.585, 0.353, 298, 0.615, 0.373, 298];
var newArray = [];

for(let i = 0; i < array.length; i += 3){
  newArray.push({ x: array[i], y: array[i+1], z: array[i+2] })
}

console.log(newArray);

UPDATED:

If you need to convert the array back to 1D vertices:

let revertArray = newArray.reduce(((acc, obj) => acc.concat(obj.x, obj.y, obj.z)), []);

JSBin: https://jsbin.com/sohakufope/edit?js,console

JSBin: https://jsbin.com/bodazugeco/1/edit?js,console

Answer №2

let newVertices = [];
for(let i = 0; i < vertices.length; i += 3) {
    newVertices.push(new THREE.Vector3(vertices[i], vertices[i + 1], vertices[i + 2]);
}

Answer №3

Here is a code snippet that may be helpful

const points = [
    0.555, 0.323, 298,
    0.585, 0.353, 297,
    0.615, 0.373, 296,
    0.123, 0.456, 295,
    0.789, 0.012, 294,
    0.234, 0.569, 293
];

if (points.length % 3 === 0) {
    const parsedPoints = [];
    for (let i = 0; i < points.length; i += 3) {
        parsedPoints.push({ x: points[i], y: points[i + 1], z: points[i + 2] });
    }
    console.table(parsedPoints);
}

Answer №4

It would have been helpful if there was actual test data provided for this scenario, but I believe the code snippet below should suffice.

const mappingKeys = ['a', 'b', 'c']
let modifiedArray = [];
let points = [0.555, 0.323, 298, 0.585, 0.353, 298, 0.615, 0.373, 298...continuous]
while (points.length) {
  result = {};
  points.slice(0, 2).forEach((value, index) => { result[mappingKeys[index]] = value });
  modifiedArray.push(result);
  points = points.slice(3);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate a fadeIn animation to a text in jQuery?

Looking for help with appending the fadeIn() jQuery function to a string that increments an integer within a paragraph. I attempted concatenation without success. Any recommendations on how to solve this issue? $p.text(parseInt($p.text(),10) + 1); ...

The JSON file is not filling the options in the dropdown menu

procedure Add the objects from the dropdown into the dropdown menu. The Json file is located in root/ajax/.json and the working file is stored in root/.html. Problem: None of the objects from the JSON file are appearing in the dropdown menu. I attempted ...

Customizing Bootstrap Vue to prevent tooltips from opening on hover

I am currently using a tooltip similar to the example shown on Toggle Tooltip: <template> <div class="text-center"> <div> <b-button id="tooltip-button-1" variant="primary">I have a tooltip</b-button> </div& ...

Running a setTimeout function within the context of a jQuery each

My goal is to animate characters one by one, but for some reason the following code isn't functioning as expected: $('.overlay-listing').hover(function(){ var idx = 1; $('.strip-hov span', this).each(function(){ if ...

Having trouble importing moment-range into your Angular 4.x application using ES6? Getting an error about incompatible call signatures?

In my Angular 4.x application, I encountered an issue while trying to import the moment-range package. The official documentation suggests using the following code: import Moment from 'moment'; import { extendMoment } from 'moment-range&apo ...

What differences occur in JavaScript when the IE Developers Tools are accessed?

When the IE Developers Tools are opened, what changes in terms of running an AJAX application? I am currently investigating a mysterious bug related to PrimeFaces dropdown lists in Internet Explorer. Sometimes these dropdowns do not open when clicked, but ...

I'm baffled by the unexpected result I'm getting when using 'foreach' in node.js

Recently delving into node.js, I've encountered a puzzling issue. I'm perplexed as to why my output appears as: ciao data data instead of: data data ciao Below is the code causing this unexpected output: fs.readdir("sender", (err, fil ...

Invoking a method in Vue.js from another component

I'm just starting out with VUE and I have a unique challenge for my project. I want to have a button on one page that triggers a function on another page. I know some may ask why not keep the button and function on the same page, but I am exploring ho ...

Complete my search input by utilizing ajax

It's only been 30 minutes since my last post, but I feel like I'm making progress with my search posts input: I've developed a model that resembles this: function matchPosts($keyword) { $this->db->get('posts'); ...

How can we use JavaScript to close a dropdown menu when the user clicks outside of it?

I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this? I attempted to use addEventListener('click', myFunction) on `document` but it did not w ...

What is the best way to cancel a setTimeout in a different function within a React JS application?

I'm currently working with the following code snippet: redTimeout = () => { setTimeout(() => { this.props.redBoxScore(); this.setState({ overlayContainer: 'none' }); }, 5000); } In addition, I h ...

Exploring Vue.js3: Simplifying Nested Array Filtering

Currently, I am in the process of sifting through an Array that contains nested arrays. To handle this task, I utilized computed and crafted a function called filteredEgg(). However, I seem to be overlooking something, as I'm only returning the main ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Vite and Transloadit encountered a type error: Unable to access properties of undefined when trying to read 'Resolver'

Currently, I am developing a Vite application using Vue 3.x that involves interactions with images/PDFs through Transloadit. While working on creating my own plugin for Transloadit integration, I encountered some issues. Initially, I managed to resolve an ...

How can the "not selected" option be disabled in a Vue Select component?

I have implemented a select box in the following manner: JS: Vue.component("v-select", VueSelect.VueSelect); new Vue({ el: "#app", data: { options: [ { countryCode: "AU", countryName: "Australia" }, { countryCode: "CA", countryName: " ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Utilizing AngularJS to extract data from a query string

After making significant progress on my previous project, I found myself in need of some final assistance that has proven to be elusive. I successfully built my entire angular controller and populated all the necessary data for the page. However, I am str ...

Clear previous loop data in PHP

I have a "show recent" pictures div on my website that I want to refresh every 20 seconds to display a new picture. However, the issue is that my current ajax call refreshes instantly instead of after 20 seconds and it fails to delete the previous data, re ...

Utilize html5 to drag and drop numerous items effortlessly

Recently, I created a basic HTML5 drag and drop feature using JavaScript. However, I encountered an issue. function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ...