Extracting single key from object to array [duplicate] - javascript

This question already has answers here:
Equivalent of Underscore _.pluck in pure JavaScript
(10 answers)
Closed 7 years ago.
I'm looking at extracting keys from an Object and push them to an array in Javascript (Nodejs). An example would be:
var obj = [{tag: 'ft001', addr: 'DB415.DBD2'}, {tag: 'ft001', addr: 'DB415.DBD6'}];
function extractKey(arr, keyName) {
// Result: ['ft001', 'ft002'];
}
How would I go about doing this?

Use Array.prototype.map():
var obj = [{tag: 'ft001', addr: 'DB415.DBD2'}, {tag: 'ft001', addr: 'DB415.DBD6'}];
function extractKey(arr, keyName) {
return arr.map(x=> x[keyName])
}
I think it's rather self-explaining.

if a typo [ 'ft001', 'ft002'], then the following would you be useful:
function extractKey() {
var result = [];
for (var index = 0; index < obj.length; index++) {
result.push(obj[index].tag);
}
return result;
// Result: ['ft001', 'ft001'];
}

Related

I want to convert array to object [duplicate]

This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings into an array of objects
(6 answers)
Closed 3 years ago.
What is the best way to convert:
from
['firstName','lastName','gender']
to
0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}
in JavaScript
You can use .map() to get the desired output:
const data = ['firstName','lastName','gender'];
const result = data.map(name => ({ title: name }));
console.log(result);
Try this code.I hope it will helps you.
var arr = ['firstName','lastName','gender']
var jsonObj = {};
for (var i = 0 ; i < arr.length; i++) {
jsonObj['title' +(i+1) ] = arr[i];
}
console.log(jsonObj)
You can simply use forEach() loop which is the easiest way:
var arr = ['firstName','lastName','gender'];
let res = [];
arr.forEach((item) => res.push({title: item}));
console.log(res);
Just to build your knowledge in Array operations you can also use reduce():
var arr = ['firstName','lastName','gender'];
let res = arr.reduce((acc, item) => {
acc.push({title: item});
return acc;
}, []);
console.log(res);

How do I write a function that returns an array containing object keys in Javascript? [duplicate]

This question already has answers here:
Javascript get object key name
(8 answers)
Closed 5 years ago.
var person = {
firstName: 'Halle',
lastName: 'Berry',
};
function names(object){
var arr= [];
for (var key in object) {
arr.push(key);
console.log(arr)
}
}
names(person);
This is what i have so far. I am trying to return an array containing the object person keys.
Object#keys makes this simple:
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
Edit: By clarifying the question (thank you!) and comments received, the implementation was close: it was missing a return statement. Including hasOwnProperty is a good practice to check whether keys belong to the object (true) or are inherited (false).
function names(object){
var arr= [];
for (var key in object) {
if (object.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr; // this was missing
}

Javascript: How to find key name in array of objects [duplicate]

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 7 years ago.
I am trying to determine if a key name is present in my array of object. As an example, how would I verify if the key with a name of 'name' equals the argument passed in my function call? Below is code to further clarify.
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var test = function(arr, propName){
var result = [];
for(var i = 0; i < arr.length; i++){
if(arr[i][propName] === propName){
result.push(arr[i][propName]);
}
}
return result;
}
func(stooges, "name");
Using underscore.js:
var names = _.pluck(stooges, 'name');
In fact this is the very example given on their page?!
So, on the basis that you knew this, but want to know how to write something similar:
function pluck(array, prop]) {
return array.map(function(entry) {
return entry[prop];
});
}
or more safely, returning an empty array if the initial array is undefined:
function pluck(array, prop]) {
return array ? array.map(function(entry) {
return entry[prop];
}) : [];
}

remove an object from an array using javascript? [duplicate]

This question already has answers here:
How do I remove an object from an array with JavaScript? [duplicate]
(15 answers)
Closed 9 years ago.
How can I remove an object from an Array by id for example:
users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}]
Say I want to remove user with id "10051" using javascript, I tried searching the internet but couldn't find anything?
plus I do not want to use underscore!
plus I do not want to use underscore!
The native method for this is .filter():
var removeId = "4567";
users = users.filter(function (user) { return user.id !== removeId; });
Note that it requires the engine be ES5-compatible (or a polyfill).
You could use .filter method of array.
users = users.filter(function(el) {return el.id !== '10051'});
for (var i = 0; i < users.length; ++i)
{
if ( users[i].id == "10051" )
{
users[i].splice(i--, 1);
}
}
var users= [{id:"10051", name:"Mike Coder"},{id:"4567", name:"Jhon Second"}];
/* users.length= 2 */
function removebyProperty(prop, val, multiple){
for(var i= 0, L= this.length;i<L;i++){
if(i in this && this[i][prop]=== val){
this.splice(i, 1);
if(!multiple) i= L;
}
}
return this.length;
}
removebyProperty.call(users,'id',"10051");
returned value: (Number) 1

How can I get member names from an object? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Getting JavaScript object key list
How to iterate json data in jquery
I have a json like this one:
var myJSONObject = {
"flowers": [
{"id":"1","name":"Red Flower","url":"flower_1.png"},
{"id":"2","name":"Purple Flower","url":"flower_2.png"},
{"id":"3","name":"Yellow Flower","url":"flower_3.png"},
{"id":"4","name":"Violet Flower","url":"flower_4.png"},
{"id":"5","name":"Purple Flower","url":"flower_5.png"}
],
"bouquet": [
{"first":[1,2,3,4,5,6]},
{"second":[1,2,3,4,5,6]},
{"third":[1,2,3,4,5,6]}
]
};
Now my questin is how can I pull only the names of members of "bouquet"...into array.
Something that will look like that : ["first","second","third"]?
In recent Firefox browsers, the following can be used (so-called Array-comprehensions):
var list = [Object.keys(i)[0] for each (i in myJSONObject.bouquet)];
If Object.keys is supported, use:
var list = []; // Create list
for (var i=0; i<myJSONObject.bouquet.length; i++) {
var keys = Object.keys(myJSONObject.bouquet[i]); //List keys
list.push(keys[0]); // Store first named key
}
In other browsers, you can use:
var list = []; // Create list
for (var i=0; i<myJSONObject.bouquet.length; i++) {
var key = myJSONObject.bouquet[i];
for (var j in key) { // Get the first named key
list.push(j); // Store named key
break; // <--- First named key, so break loop
}
}
for(var i=0; i< myJSONObject["bouquet"].length; i++)
{
var o = myJSONObject["bouquet"][i];
document.write(Object.keys(o) + "<br>");
}
output: first second third
JSFiddle for confirmation
if you are in an environment that supports modern ECMA additions, you can use Object.keys (docs here) or you can polyfill your own if you need to, something like this:
function getKeys(obj) {
var ret = [], prop;
for (prop in obj) {
if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
ret.push( prop );
}
}
return ret;
};
Usage:
var keys = getKeys({ foo: "a", bar: "b" }); // -> ['foo', 'bar']
hope that helps! cheers.

Categories

Resources