how to get string from array using angularjs or javascript - javascript

var array = [
{id: 1, text: "one"},
{id: 2, text: "two"},
{id: 3, text: "three"},
{id: 4, text: "four"},
{id: 5, text: "five"}
];
var name = array.find(function(item){
return item.id == $localStorage.id;
});
returns me {id: 2, text: "two"}
expected two only string nothing else should print

You can first find the object and then get the text property by checking if the find() operation actually returned a object or it is undefined.
var array = [{
id: 1,
text: "one"
},
{
id: 2,
text: "two"
},
{
id: 3,
text: "three"
},
{
id: 4,
text: "four"
},
{
id: 5,
text: "five"
}
];
var findObj = array.find(function(item) {
return item.id == 2;
});
//check if findObj is defined or not
var name = findObj? findObj.text: null;
console.log(name);
You can also use destructuring to get that text value directly from find() if you are sure the object exist for that localStorage value. Otherwise, it will raise error.
var array = [{
id: 1,
text: "one"
},
{
id: 2,
text: "two"
},
{
id: 3,
text: "three"
},
{
id: 4,
text: "four"
},
{
id: 5,
text: "five"
}
];
var {text} = array.find(function(item) {
return item.id == 2;
});
console.log(text);

What you did returns the element at the position where item.id == $localStorage.id. If you want to get the text, then after the element is returned in var name, you just do name.text because array.find() returns the element that passed the logical operation.

You can use filter and map. This way you can customize your filtered result the way you want.
var array = [
{id: 1, text: "one"},
{id: 2, text: "two"},
{id: 3, text: "three"},
{id: 4, text: "four"},
{id: 5, text: "five"}
];
var name = array.filter(a=> a.id === 2).map(b=> {return b.text});
console.log(name)

You should retrieve property text of found object:
var object = array.find(function(item){
return item.id === $localStorage.id;
});
var name = object.text;

If you like to use es6 syntax, you can write like this.
You did everything good except, you needed to get specific object value.
const array = [
{ id: 1, text: "one" },
{ id: 2, text: "two" },
{ id: 3, text: "three" },
{ id: 4, text: "four" },
{ id: 5, text: "five" }
];
// So here i use same find as you did.
let object = array.find(item => {
return item.id == $localStorage.id;
});
// And assigning text property of object to variable 'name'
// since object, can be undefined, using OR empty object,
// so no error will be thrown if so.
let { text: name } = object || {};
console.log(name);
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find:
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Try like this way to get text attribute value while using find by id
var array = [{
id: 1,
text: "one"
},
{
id: 2,
text: "two"
},
{
id: 3,
text: "three"
},
{
id: 4,
text: "four"
},
{
id: 5,
text: "five"
}
];
var name = array.find(function(item) {
return item.id == 2;
}).text;
console.log(name);

find will return the object that satisfy the condition
var object = array.find(function(item) {
return item.id == $localStorage.id;
});
var name = object? object.text: null;
console.log(name);

Related

Angular search a key in an object and change the value of another key

I have this data below.
I need to be able to search in the objet for the id or name key and then change the 'show' key to a different value.
How example:
Search the data for id value 2 and change the show value to false.
data = [
{
id: 1,
name: 'one',
show: false;
title: 'title1',
data: [
{
id: 1,
description: 'some description'
},
{
id: 2,
description: 'some other description'
}
]
},
{
id: 2,
name: 'two',
show: true;
title: 'title2',
data: [
{
id: 1,
description: 'some description'
},
{
id: 2,
description: 'some other description'
}
]
}
]
How can I do this?
You can use the findIndex method, and then access your array using the found Index and change any property you want, here's some code that match your use case
let index = data.findIndex((x) => x.id == THE_ID_YOU_ARE_LOOKING_FOR);
if(index > -1) {
data[index].show = THE_VALUE_YOU_WANT;
}
You can also use normal array find method.
let item = data.find(x=>x.id===REQUIRED_ID);
if(item) item.show = false

Map over two arrays to see if one property matches, then push specific info into the first array

New to javascript and trying to learn! I am trying to map through two array of objects, and if a certain property matches, pull in specific information into the first array.
let result;
let arrNames = [{
id: 10
name: "A"
}, {
id: 11,
name: "B"
}, {
id: 12,
name: "C"
}, }, {
id: 13,
name: "A"
}, {
id: 14,
name: "B"
}]
let arrInfo = [{
name: "A",
info: "AAA"
}, {
name: "B",
info: "BBB"
}, {
name: "C",
info: "CCC"
}]
If arrNames.name == arrInfo.name, I would like push info into the names array.
Desired result:
let arrNames = [{
id: 10
name: "A",
info: "AAA"
}, {
id: 11,
name: "B",
info: "BBB"
}, {
id: 12,
name: "C",
info: "CCC"
}, }, {
id: 13,
name: "A",
info: "AAA"
}, {
id: 14,
name: "B",
info: "BBB"
}]
What I've tried:
const res = arrInfo.map((el, index) => {
if(el.name == arrNames[index].name)
arrNames.push(el.info)
}
^ This obviously doesn't work -- but I'm wondering if extend or push would be appropriate here.
Thanks in advance for your help (apologies that this is probably a dupe).
Convert arrInfo to a Map, with the name as the key. Now map arrNames and add the info you get from arrInfoMap using the name. Use object spread to combine both objects:
const arrNames = [{"id":10,"name":"A"},{"id":11,"name":"B"},{"id":12,"name":"C"},{"id":13,"name":"A"},{"id":14,"name":"B"}]
const arrInfo = [{"name":"A","info":"AAA"},{"name":"B","info":"BBB"},{"name":"C","info":"CCC"}]
const arrInfoMap = new Map(arrInfo.map(o => [o.name, o]))
const result = arrNames.map(o => ({ ...o, ...arrInfoMap.get(o.name) }))
console.log(result)
You can do something like this:
let arrNames = [
{
id: 10,
name: 'A'
},
{
id: 11,
name: 'B'
},
{
id: 12,
name: 'C'
},
{
id: 13,
name: 'A'
},
{
id: 14,
name: 'B'
}
];
let arrInfo = [
{
name: 'A',
info: 'AAA'
},
{
name: 'B',
info: 'BBB'
},
{
name: 'C',
info: 'CCC'
}
];
// do this
const result = arrNames.map((item) => {
const newItem = item; // here we define a new object that is the same as your object that is currently looped up to in your arrNames array
// loop your second array over this currently looped to object, seeing if the name matches
arrInfo.forEach((item2) => {
if (item.name === item2.name) {
newItem.info = item2.info; // if they do set a new property for your new object called info as the info from item 2 of this arrInfo array
}
});
// return this new object whether or not there was a match for the name property
return newItem;
});
console.log(result);
So the thing with your map method is that you need to remember to return something at the end of your callback function. You are simply pushing to an array, which is like using .map as a forEach. Map makes one array into another array of the same length. Here you are trying to make a new array where the array element being looped over will have an extra info property should it match your second array arrInfo's name.
So you what you can do is a forEach inside your map to check if they match, if so add a new property to your arrayNames element and return that as the new element for your newly created array. Hope that helped, please ask for clarifications if you need in the comments.

add an object to an array if it doesn't have the same key with one of the objects in the array

I'm using Lodash. I have the array below:
const array = [{id:1,name:a},{id:2,name:b},{id:3,name:c},{id:4,name:d},{id:5,name:e}];
and I'm about to add another object to this array but before that, I need to check if the new object's name is already in the array or not and if there is one with the name I won't add the new object anymore.
I know some ways to do it, for instance, a loop with _.map, but want to make sure if there is an easier way.
You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.
With native javascript , you can use findIndex, this will return the index of the object where the name matches. If it returns -1 then there is no such object with same name. In that case update the array.
const array = [{
id: 1,
name: 'a'
}, {
id: 2,
name: 'b'
}, {
id: 3,
name: 'c'
}, {
id: 4,
name: 'd'
}, {
id: 5,
name: 'e'
}];
let newObjToAdd = {
id: 1,
name: 'z'
};
let newObjNotToAdd = {
id: 1,
name: 'a'
}
function updateArray(obj) {
let k = array.findIndex((item) => {
return item.name === obj.name;
})
if (k === -1) {
array.push(obj)
} else {
console.log('Array contains object with this name')
}
}
updateArray(newObjToAdd);
console.log(array)
updateArray(newObjNotToAdd);
You don't need lodash for some. You get that with native JS too (ES6):
const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];
console.log(array.some(e => e.name === 'a'));
if (!array.some(e => e.name === 'z')) {
array.push({id: 5, name: 'z'});
}
console.log(array);
Doing this with lodash is few chars shorter but here is how you could do it with ES6 and Array.some:
const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];
const maybeUpdate = (arr, obj) => {
if(!array.some(x => x.id == obj.id))
array.push(obj)
}
maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
maybeUpdate(array, {id: 12, name: "F"}) // will insert
console.log(array)
Same idea with lodash and _.some would be:
const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];
const maybeUpdate = (arr, obj) => {
if(!_.some(array, {id: obj.id}))
array.push(obj)
}
maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
maybeUpdate(array, {id: 12, name: "F"}) // will insert
console.log(array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Note that you could also use various other ways to get the same result. Array.find or _.find would work as well since all you have to do is to check if there was a hit:
const maybeUpdate = (arr, obj) => {
if(!_.find(array, {id: obj.id})) // or if(!array.find(x => x.id == obj.id))
array.push(obj)
}

method find javascript deep array object RN react native

Here is a part of my object
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = fr;
const anyId = 3;
I don't know why when doing the following:
const result = category[lang].list.find(item => item.id === anyId) console.log(result)
Throws the following:
// undefined category[lang].list.find(item => item.id === anyId) is not
a function, or just undefined
same result for .map or .filter
console.log(category) returns no error
console.log(category[lang]) returns no error
console.log(category[lang].list) returns no error
but anything else will return an error.
It drives me crazy, any help will be highly appreciated.
Use const lang = "fr" instead of const lang = fr, because fr is an undefined variable but "fr" is a string. So you'll get category["fr"] instead of category[fr].
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = "fr";
const anyId = 3;
const result = category[lang].list.find(item => item.id === anyId)
console.log(result)
You want category.fr not just fr, as the variable fr does not exist.
Now that lang contains your fr object, you can simply do a .find() on lang.list as below:
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
// Fill param from a variable, or anything, as long as it's a string:
const param = 'fr';
// Use brackets here, as you want `category.fr` and not `category.param`:
const lang = category[param];
//Or you can simply use:
//const lang = category.fr; //If this is not a parameter, or user input
const anyId = 3;
console.log(lang);
console.log(lang.list.find(item => item.id === anyId));
It works on mdn sandbox
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'ici'},
{id: 3, label: 'demain'},
{id: 4, label: 'matin'},
]
}
};
var lang ='fr';
var catID = 3;
console.log(lang);
console.log(catID);
console.log(category);
console.log(category[lang]);
console.log(category[lang].list);
var found = category[lang].list.find(function(element) {
return element.id === catID;
});
console.log(found.label); // demain
just add a return inside the callback function,
but it still doesn't work on react-native
so the problem remains

Underscore.js get an array of unique objects

I have 2 arrays of objects. There are duplicates between the arrays. I want to merge them into 1 array of all unique objects (so no duplicates).
How can I do this by comparing the "id" of each object?
Underscore.js has a method called _.uniq(). It looks to be correct, but I can't get the syntax for the "iterator" argument correct.
var firstArray = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var secondArray = [{ id: 2, name: "boop" }, { id: 3, name: "baz" }];
firstArray.push(secondArray);
var myUniqueArray = _.uniq(firstArray, false, ???);
myUniqueArray // [{ id: 1, name: "foo"}, { id: 2, name: "bar" }, { id: 3, name: "baz" }];
You should be able to achieve this with _.uniq method used with second parameter of the property name to be used to filter items:
var firstArray = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var secondArray = [{ id: 2, name: "boop" }, { id: 3, name: "baz" }];
var result = _.uniq(firstArray.concat(secondArray), 'id');
alert(JSON.stringify(result, null, 4));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The following should do it:
var myUniqueArray = _.uniq(firstArray.concat(secondArray), false, function (obj) {
return obj.id;
});
The iteratee here will produce a value on which uniqueness is checked, in this case the id property value.
Here's a JSFiddle.

Categories

Resources