0

Hello i am trying to make cms with threejs, and i want to add the json attributes to a mesh of threejs. I can retrieve the json attributes separate with:

console.log(Articles.results[i].id);

but i want for example to have mesh.id etc.

my json output is:

{id: 6, title: "ytc zjzx", summary: "zxv xzcv xcvzx", content: "zxvxcbvcx bcvbdf", publicationDate: 1506632400}
length
:
2
__proto__
:
Array(0)
totalRows
:
2
__proto__
:
Object

And my code until now:

function addGeometry() {
    var geometry = new THREE.BoxBufferGeometry(25, 25, 25);
    var material = new THREE.MeshBasicMaterial({color:0x00ff44});


for(var i = 0; i < Articles.results.length; i += 1){

console.log(Articles);

mesh = new THREE.Mesh( geometry, material );

    mesh.position.y =Math.random() * ((HEIGHT-10) - (HEIGHT+10));
    mesh.position.x =Math.random() * ((HEIGHT-10) - (HEIGHT+10));


     mesh.updateMatrix();
     mesh.matrixAutoUpdate = false;
     scene.add( mesh );

}

1 Answer 1

1

You can use Object.keys() to get the properties of your object. Then use bracket notation to assign that property to your mesh:

// Assuming this is your object
var obj = Articles.results[i];    

var keyNames = Object.keys(obj);

keyNames.forEach(v => {
    // v is the name of the property (e.g. "id", "title")
    mesh[v] = obj[v]
});

You then assign them to your mesh and you should be able to access them later. The good thing about using this method is that it's very flexible. It will work all the same even if your JSON changes.

Here's a working Pen.

Be advised that Object3D contains an id property already, so you'll be overwriting that. Check first to see what you put in your JSON.

Another option would be to attach an object to the mesh and assign the values there. Something like:

mesh.info[v] = obj[v];

And then you can access it like mesh.info.id without losing previous values.

Sign up to request clarification or add additional context in comments.

5 Comments

it gives me: Uncaught TypeError: Cannot set property 'id' of undefined Can i have it also as a mesh and have the json properties?
i think it is better the Object.assign(target, ...sources) method.It does not give me an error but assign the number of array object.like this: ["0", "1", "2", "3", "4", "uuid", "name" ...
Check the edit, I added an example. Also, the error is saying your mesh var is undefined.
there is no id in the values of the mesh, i will check it again along with the Pen.Also the mesh.info[v] seems nice, more tidy.
It works, i had the mesh var as global then put the Objects.keys and after created the new mesh.I had to do it with your order.I will check also the id bypass or the solution with the info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.