0

I get this data from the backend

let procedure_word_count = [{"slug":"new","name":"New","count":1},{"slug":"no-need","name":"No Need","count":2},{"slug":"why","name":"Why","count":2}]

My goal is to create a dimensional array that extracts the name and count from the "procedure_word_count"

let newArray = "[['New', 1], ['No Need', 2], ['Why', 2]]"
2
  • 1
    Why is newArray a string? Commented Sep 15, 2021 at 14:32
  • "procedure_word_count" = [...] is invalid syntax Commented Sep 15, 2021 at 14:33

3 Answers 3

2

You can always map it and create an array from the object:

let example = [
  {"slug":"new","name":"New","count":1},
  {"slug":"no-need","name":"No Need","count":2},
  {"slug":"why","name":"Why","count":2}
];

let result = example.map((item) => [item.name, item.count]);
console.log(result);

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

Comments

1

The map method creates a new array with the results of calling a function for every array element so it's a classic for this one. for each iteration the function will return an array containing the selected keys values.

const arr = [{"slug":"new","name":"New","count":1},{"slug":"no-need","name":"No Need","count":2},{"slug":"why","name":"Why","count":2}];

const res = arr.map(x => [x.name, x.count]);
console.log(res);

Comments

1

The JSON you retrieve from the server can be iterated over using the .map() method.

.map() iterates over each element and builds an array.. The function returns whatever you want - in this case the name and count properties.

const input = [{"slug":"new","name":"New","count":1},{"slug":"no-need","name":"No Need","count":2},{"slug":"why","name":"Why","count":2}];

const output = input.map(o=>[o.name,o.count]);

console.log(output);

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

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.