Sorry I'm kind of new to JS; I have an array of object; how can I get the name of the object which has the key "user_key3" and obviously without having a loop and have a condition.
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}]
Please let me know if you need more clarification
Thanks
You can do it the functional way, like this
var name;
arr.forEach(function(currentObject) {
if (currentObject.key === "user_key3") {
name = currentObject.name;
}
});
If you want to short-circuit on the first match, you can use Array.prototype.some, like this
var name;
arr.some(function(currentObject) {
if (currentObject.key === "user_key3") {
name = currentObject.name;
return true;
}
return false;
});
The OP had mentioned obviously without having a loop and have a condition. I would do it as below:
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}];
var keyValMap = arr.map(function(n) { return n.key } );
var arrIndex = keyValMap.indexOf('user_key3');
alert(arr[arrIndex].name);
Fiddle
You'll have to iterate and check for the key
var user_name;
for (var i=0; i<arr.length; i++) {
if ( arr[i].key === 'user_key3' ) {
user_name = arr[i].name;
break;
}
}
FIDDLE
You've edited the question to include
obviously without having a loop and have a condition
but a loop and a condition is by far the most efficient and cross-browser way to do this, so why would you "obviously" not want this ?
An inefficient yet concise solution would be
var keyarr = arr.map(function(x) { return x.key } );
//keyarr is list of keys
var index=keyarr.indexOf("user_key3");
//arr[index] is your answer. Index will be -1 if the key doesn't exist
In general, finding an item that satisfies some arbitrary property in an array requires you to loop over the array:
function find(arr, name) {
for (var i=0; i<arr.length; i++) {
if ( arr[i].key === name ) {
return arr[i];
}
}
}
Then to find it,
var obj = find(arr, 'user_key3');
Using more functional solutions to find the item is fine too, but you still end up looping in some way.
However, if you are doing lookups by key, then an array of key-value pairs is not the best data structure. I would suggest using an object directly:
var map = {
'user_key1': 'user1',
'user_key2': 'user2',
'user_key3': 'user3'
}
Then lookup is simply:
map['user_key3'];
Try this - underscore.js
For Your Example -
_.where(arr, {key: "user_key3"});
You cannot do such thing with Objects in Javascript. Though here you have a combination of callbacks and loop:
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}];
arr.forEach(function(elme){
for(var g in elme)
{
if(elme[g] == 'user_key3')
{
console.log("Found the value: "+g+" : "+elme[g]);
};
}
});
Related
I need to check if the duplicate key value present inside the json array using Angular.js. I am explaining my code below.
var result=[{
"email":'a#gmail.com',
"title":'hello',
"start":'yes'
},{
"email":'a#gmail.com',
"title":'hello',
"start":'yes'
},{
"email":'b#gmail.com',
"title":'ggggg',
"start":'No'
},{
"email":'g#gmail.com',
"title":'hel',
"start":'No'
},{
"email":'b#gmail.com',
"title":'ggggg',
"start":'No'
}];
if (result.length > 0) {
angular.forEach(result,function(obj2){
var data={'title':obj2.mname,'start':obj2.date};
evtArr.push(data);
})
}
Here my requirement is before pushing the data into evtArr it will check the duplicate value using the key- email if one set of value belongs to one email (i.e-a#gmail.com) is already pushed into evtArr then other will remove.
You can use array#reduce and create an object using email as key and object as value. Take out all the values from the object using Object.values().
var result=[{ "email":'a#gmail.com', "title":'hello', "start":'yes' },{ "email":'a#gmail.com', "title":'hello', "start":'yes' },{ "email":'b#gmail.com', "title":'ggggg', "start":'No' },{ "email":'g#gmail.com', "title":'hel', "start":'No' },{ "email":'b#gmail.com',"title":'ggggg', "start":'No' }],
output = Object.values(result.reduce((r,o) => {
r[o.email] = Object.assign({},o);
return r;
},{}));
console.log(output);
Here below is a simple and easy to understand solution for you.
First, push only the results into resultFinal array if the result with same email is not already pushed into that array.
let resultFinal = [];
result.forEach((resI) => {
if (resultFinal.findIndex(resF => resF.email === resI.email) === -1) {
resultFinal.push(result);
}
});
After you have your resultFinal array, run a map and return objects comprising only of title and start for each of the elements.
resultFinal = resultFinal.map((resF) => {
return {title: resultf.title, start: resultf.start};
});
Hope this helps you.
Try this Code.understand easily
var result = [{
"email": 'a#gmail.com',
"title": 'hello',
"start": 'yes'
}, {
"email": 'a#gmail.com',
"title": 'hello',
"start": 'yes'
}, {
"email": 'b#gmail.com',
"title": 'ggggg',
"start": 'No'
}, {
"email": 'g#gmail.com',
"title": 'hel',
"start": 'No'
}, {
"email": 'b#gmail.com',
"title": 'ggggg',
"start": 'No'
}];
if (result.length > 0) {
var ArrayPush = [];
for (i = 0; i < result.length; i++) {
var obj = {}
obj.email = result[i].email;
obj.title = result[i].title;
obj.start = result[i].start;
var Getdistinctdate=ArrayPush.filter(function(element){
return element.email==result[i].email;
});
if(Getdistinctdate.length==0){
ArrayPush.push(obj);
}
}
}
I've got an array of three people. I want to add a new key to multiple objects at once based on an array of indices. Clearly my attempt at using multiple indices doesn't work but I can't seem to find the correct approach.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
}
];
array[0,1].title = "Manager";
array[2].title = "Staff";
console.log(array);
Which returns this:
[
{
"name": "Tom",
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
But I'd like it to return this.
[
{
"name": "Tom",
"title": "Manager"
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
You cannot use multiple keys by using any separator in arrays.
Wrong: array[x, y]
Correct: array[x] and array[y]
In your case, it will be array[0].title = array[1].title = "manager";
1st method::
array[0].title = "Manager";
array[1].title = "Manager";
array[2].title = "Staff";
array[0,1] will not work.
2nd method::
for(var i=0;i<array.length;i++) {
var msg = "Manager";
if(i===2) {
msg = "Staff"
}
array[i].title = msg
}
You can use a helper function like this
function setMultiple(array, key, indexes, value)
{
for(i in array.length)
{
if(indexes.indexOf(i)>=0){
array[i][key] = value;
}
}
}
And then
setMultiple(array, "title", [0,1], "Manager");
Try this: `
for (var i=0; var<= array.length; i++){
array[i].title = "manager";
}`
Or you can change it around so var is less than or equal to any n range of keys in the index.
EDIT: instead make var <= 1. The point is to make for loops for the range of indices you want to change the title to.
Assuming that you have a bigger set of array objects.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
},
.
.
.
];
Create an object for the new keys you want to add like so:
let newKeys = {
'Manager': [0,2],
'Staff': [1]
}
Now you can add more such titles here with the required indexes.
with that, you can do something like:
function addCustomProperty(array, newKeys, newProp) {
for (let key in newKeys) {
array.forEach((el, index) => {
if (key.indexOf(index) > -1) { // if the array corresponding to
el[newProp] = key // the key has the current array object
} // index, then add the key to the
}) // object.
}
return array
}
let someVar = addCustomProperty(array, newKeys, 'title')
I would like to transform the below JSon. The input JSon array can be of any size. I know its a basic question but I can't find the duplicate.
var input = [{
"value": 1
}, {
"value": 2
}]
var output = [{
"key": {
"value": 1
}
}, {
"key": {
"value": 2
}
}]
Appreciate all the help.
Create a new array and use Array#forEach to push an object with key = key and a currently iterated object from input as the value.
var input = [{value:1},{value:2}],
result = [];
input.forEach(v => result.push({ 'key': v }));
console.log(result);
Try using this, this should solve your problem
output = input.map(value => ({ "key": value }) );
console.log(output);
I used ES6 for simplicity, but this does exactly the same.
I think this will be the most oldschool and hands-on way of doing this.
var input = [{
"value": 1
}, {
"value": 2
}],
output = [],
newItem,
i = 0, ii = input.length;
for(i; i<ii; i++){
newItem = {};
newItem.key = {"value":input[i].value};
output.push(newItem);
}
console.log(output)
I have an array of objects and would like to check if a specific key/value exists, I'm currently using a for..in loop but was wondering if there is shorter/better way to do this?
JS
var models = [
{
"id": 1,
"name": "James"
},
{
"id": 2,
"name": "Ken"
},
{
"id": 3,
"name": "Jason"
}
];
function checkNameExists(name) {
for( var model in models ) {
if (models[model].name === name) {
return true;
}
}
}
var nameExists = checkNameExists("Ken");
if(nameExists) {
console.log('Name exists');
}
JSFiddle: http://jsfiddle.net/kyllle/c21opmj8/1/
You can use underscore's some function :
var nameExists = _.some(models, function (elem) {
return elem.name == "Jason"
})
or in a shorter version as Ahmad Mageed suggested :
var useFound = _.some(models,{ 'name': 'Jasonn' });
Here is a JSFiddle : http://jsfiddle.net/c21opmj8/2/
In plain vanilla, you can use some on any array
function checkNameExists(name) {
return models.some(function(e){return e.name===name;});
}
(can be used without the function as well since you don't need the loop)
If arrow functions get wide spread support, readability will be better ;) Then you could use models.some(e => e.name===name)
Without depending on external libraries, Array.filter() does the job:
models.filter( (x) => x.name==="Jason" )
Array.find() finds first occurrence and stops, hence it's faster.
Here is a solution with underscore
console.clear();
var models = [
{
"id": 1,
"name": "James"
},
{
"id": 2,
"name": "Ken"
},
{
"id": 3,
"name": "Jason"
}
];
var tab_name = _.map(models, function(x){return x.name});
var name_exists = _.contains( tab_name , 'Ken')
if( name_exists ) {
console.log('Name exists');
}
I have two js arrays already, say: names and values (with the same length), now I would like to construct a json object in certain format? For example:
names = ["label1","label2","label3"];
values = [[[0,1],[1,9],[2,10]],[[0,89],[1,91],[2,1]],[[0,1],[1,9],[2,10]]];
I would like to have a json array data_spec in this format:
[{
label:"label1",
data:[[0,1],[1,9],[2,10]]
},
{
label:"label2",
data:[[0,89],[1,91],[2,1]]
},
{
label:"label3",
data:[[0,1],[1,9],[2,10]]
}]
Could anyone tell one how? Thanks a lot!
For a bit of variety and a check,
var data_spec = [];
if (names.length != values.length) {
// panic, throw an exception, log an error or just return an empty array
} else {
for (var i=0, name; name = names[i]; i++) { // assuming a non-sparse array
data_spec[i] = {
label : name,
data : values[i]
};
}
}
That is, non-sparse and not containing anything else that would evaluate to false.
If your framework has an each function added to Array and you don't care about performance,
var data_spec = [];
names.each(function(name) {
data_spec.push({ label : name, data : values[names.indexOf(name)] });
});
If your framework is a clean one like Dojo and puts it somewhere else (ex is Dojo),
var data_spec = [];
dojo.forEach(names, function(name) {
data_spec.push({ label : name, data : values[names.indexOf(name)] });
});
If your framework has an each function that returns an Array of identical length with the results of every operation at their expected position,
var data_spec = arrayOfResultsEach(names, function(name) {
return { label : name, data : values[names.indexOf(name)] };
});
These are just for illustration, indexOf inside loops of arbitrary length is a major code smell.
Just use a loop (make sure the two arrays are of same length)
result = [];
for(var i=0, len=names.length; i < len; i++) {
result.push({label: names[i], data: values[i]});
}
var myArray =
[{
"label": "label1",
"data" :
{
"0": "1",
"1": "9",
"2": "10"
}
},
{
"label": "label2",
"data" :
{
"0": "89",
"1": "91",
"2": "1"
}
},
{
"label": "label3",
"data" :
{
"0": "1",
"1": "9",
"2": "10"
}
}];
alert(myArray[0].data[2]);