Home > other >  Get name from JSON JS
Get name from JSON JS

Time:11-13

In JS I get a response in string ex.

[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]

And from that I want to only have names, ex.

[{"name":"Cubsonx"},{"name":"Paulina453"}]

and then render every name that is on the list in an discord.js embed fields.

CodePudding user response:

Parse the string to an object:

const jsonObj = '[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]';

const obj = JSON.parse(jsonObj);

then map the array to the desired one:

const names = obj.map((item) => ({ name: item.name }));

and if you need a string again, then stringify the result:

const stringNames = JSON.stringify(names);

CodePudding user response:

Using _.map from lodash:

const getNames = function(obj) {
  return {
    name: obj.name
  }
}

const data = [{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]


const newArray = _.map(data, getNames)
console.log(newArray) //result: [{"name":"Cubsonx"},{"name":"Paulina453"}]

Using plain JS Array.map MDN: Array.prototype.map

const data = [{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]

const newArray = data.map((item) => ({ name: item.name }))
console.log(newArray) //result: [{"name":"Cubsonx"},{"name":"Paulina453"}]

CodePudding user response:

arr.map((el) => el.name);

This will return an array with names.

CodePudding user response:

Take JSON into obj variable and do

obj.map((element) => element.name)

This will return names

  • Related