Reputation: 61
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.
Upvotes: 2
Views: 5992
Reputation: 3193
In case if you want the value only, The following example will give you only names in a 1d array
var array = [ {"name":"Joe", "age":17},{"name":"Bob", "age":17},{"name":"Carl", "age": 35}];
var res = array.map(({name}) => (name));
console.log(res);
Upvotes: 3
Reputation: 150
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>
Upvotes: 3
Reputation: 681
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.
Upvotes: 1
Reputation: 2827
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` */
})
Upvotes: -1
Reputation: 30739
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:
var array = [ {"name":"Joe", "age":17},{"name":"Bob", "age":17},{"name":"Carl", "age": 35}];
var res = array.map(({name}) => ({name}));
console.log(res);
Upvotes: 5
Reputation: 23859
You can use Array#map
to do that. Destructure the name from the object and return a new object with only the name.
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);
Upvotes: 2
Reputation: 321
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;
Upvotes: 1