2

I try to access to my data json file:

[{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}

This is my approach:

data[0].name;

But like this I get only the result:

Animals

But I would need the result:

Animals, Cats

2 Answers 2

2

You are accessing only the name property of 0th index of project array. To access all object at a time you need to loop over the array. You can use Array.map for this.

var data = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}]

var out = data[0].project.map(project => project.name).toString()

console.log(out)

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

9 Comments

Thank you, but this is confusing me, because data in my example is actually replacing project and in your example you have data and project two different things. I do not know how to transfer this now into my code "render": function (data, type, row) {if(Array.isArray(data)){return data.name;}}
as per your example. If data is the provided json, then data[0].name is Maria not Animals. If you are getting Animals it means data is actually your given json => project
if data is projects array: just do data.map(project => project.name).toString()
data = project. This would mean data.map(data => data.name).toString()
Is it possible to just write this data[,].name
|
1

If that's your actual data object, then data[0].name would give you "Maria". If I'm reading this right, though, you want to get all the names from the project array. You can use Array.map to do it fairly easily. Note the use of an ES6 arrow function to quickly and easily take in the object and return its name.

var bigObject = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}];
var smallObject = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];

console.log("Getting the names from the full array/data structure: "+bigObject[0].project.map(obj => obj.name))
console.log("Getting the names from just the project array: "+smallObject.map(obj => obj.name))

EDIT: As per your comment on the other answer, you said you needed to use the solution in this function:

"render": function (data, type, row) {if(Array.isArray(data)){return data.name;}}

To achieve this, it looks like you should use my bottom solution of the first snippet like so:

var data = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];

function render(data, type, row){
  if(Array.isArray(data)){
    return data.map(obj => obj.name);
  }
};

console.log("Render returns \""+render(data)+"\" as an array.");

1 Comment

@Jarla Glad I could help! Good luck on whatever you're using this for. :)

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.