how to return a specific key from an array
please can anyone help me with some code to get specific data from an array here's is my array
var array = [
{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
]
just want to return name and its values without returning age
thanks in advance.
6 Answers
6
Simple enough to access the name attribute of the object you simply need to reference the item in the array and select the name like so:
array[i].name;
Use Array.map()
with array destructuring method so that you get only the name
key-value. Array.map()
will have only one parameter so you do not need to mention return
there:
Array.map()
name
Array.map()
return
var array = [ {"name":"Joe", "age":17},{"name":"Bob", "age":17},{"name":"Carl", "age": 35}];
var res = array.map(({name}) => ({name}));
console.log(res);
You could create a helper function to get a by property object off that array :
var persons = [
{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
];
function getElement(personList, property, comparable) {
var arraySize = personList.length;
for(var i = 0; i < arraySize; i++) {
if (personList[i][property] == comparable) {
return personList[i]
}
}
return {"name":null, "age":null};
}
console.log(getElement(persons, "name", "Joe")); // outputs { "name": "John", "age" : 17}
console.log(getElement(persons, "name", "Fake John")); // outputs { "name": null, "age" :null}
This way you can retrieve your person object by any property he has.
Try using the jQuery.inArray() function. I hope it will help you.
function functionname(){
var names = [ {"name":"Joe", "age":17},{"name":"Bob", "age":17},{"name":"Carl", "age": 35}];
var name = $('#name').val();
if(jQuery.inArray(name, names)) {
alert(name +" Is In Array");
} else {
alert(name + ' Is NOT In Array...');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name"/>
<button onclick="functionname()" >Submit</button>
You can use Array#map
to do that. Destructure the name from the object and return a new object with only the name.
Array#map
See the working demo below:
var array = [{
"name": "Joe",
"age": 17
}, {
"name": "Bob",
"age": 17
}, {
"name": "Carl",
"age": 35
}];
var result = array.map(({name, ...rest}) => ({name}));
console.log(result);
All these Array.Map functions facepalm
var array = [
{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
]
array.forEach((entry) => {
console.log(entry.name) /* Do whatever you want with `entry.name` */
})
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
please add what "fetch specific data" means.
– Nina Scholz
6 hours ago