How to get value in an object array by key - arrays

how can I get value in an object array by a key, which is also in this object array.
the object array looks like this:
const objectArray = [
{key: "1", value: "12321"},
{key: "2", value: "asdfas"}
]
I have now the value of key, e.g. key = 1, but I want to get 12321 as result.
any solution?

You can use .find() to achieve it.
Try this:
Working Demo
this.objectArray.find(x => x.key == "1").value
To handle exception, if the item doesn't exists in the array, do this:
let item = this.objectArray.find(x => x.key == "1")
this.value = item ? item.value : null

You can do this using filter() and use the value of the key you already have.
const objectArray = [
{key: "1", value: "12321"},
{key: "2", value: "asdfas"}
]
const el = objectArray.filter(item => item.key == 1)[0];
el
? console.log(el.value) // gives 12321
: console.log('none listed')

objectArray.find(e => e.key == "1")
ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

objectArray.forEach(function(item) {
Object.keys(item).forEach(function(key) {
console.log("key:" + key + "value:" + item[key]);
});
});

Related

React native: how to find an item in array?

i have this array:
var arr = [{"3": "2"}, {"2": "6"}, {"4": "7"}, {"5": "9"}];
I cant get the value by index, i am trying to do this:
console.log(arr[3]); //output needed: 2.
console.log(arr[5]); //output needed: 9.
...
any help please?
UPDATE:
I am trying to add sub categories to an array with the main category:
const [subcatsSelectedForNow,setSubCatsSelectedForNow]=useState([]);
const selectCat = (catid,maincat)=>{
var arr=subcatsSelectedForNow || [];
arr.push({
[catid]:maincat
});
setSubCatsSelectedForNow(arr);
};
const arr = [{ 3: "2" }, { 2: "6" }, { 4: "7" }, { 5: "9" }];
You simply can't achieve your accepted behavior using console.log(arr[3]);
First you need to find whether the property(catid) exist in the array or not & if it is exist then you can get the object value as below,
const find = (num) => {
let obj = arr.find((item) => item[num]);
return obj && obj[num];
};
console.log(find(3)); //Output -> 2
Hope this helps you. Feel free for doubts.

How to filter object and return only key value if key is uppercase

var params = {
"rn": "AuditTrailLogon",
"Dateange": "lastquarter",
"App": "20000",
"ts": "AuditTrailLogon"
}
let filtered = Object.keys(params)
.filter(key => key.toUpperCase() === key);
console.log("filtered", filtered);
How can I filter the object and return only the ones that are uppercase keys
var params = {
"rn": "AuditTrailLogon",
"Dateange": "lastquarter",
"App": "20000",
"ts": "AuditTrailLogon"
}
Tried .filter method but it return null
let filtered = Object.keys(params )
.filter(key => key.toUpperCase() === key);
console.log("filtered", filtered); returns null []
how to get
{
"Dateange": "lastquarter",
"App": "20000",
}
Convert the object to entries (Object.entries()), filter the entries(I've used a regex), and then convert back to object with Object.fromEntries():
const params = {
"rn": "AuditTrailLogon",
"Dateange": "lastquarter",
"App": "20000",
"ts": "AuditTrailLogon"
}
const uppercaseTest = /^[A-Z]/
const result = Object.fromEntries(
Object.entries(params)
.filter(([key]) => uppercaseTest.test(key))
)
console.log(result)
You are converting the key to Uppercase, so when you compare the keys you get something like this:APP === App, but if you want to compare the keys just by the first character of the key capitalized, you can do something like this:
let filtered = Object.keys(params )
.filter(key => {
let capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);
return capitalizedKey === key
});

How can I map an object in order to change it?

I need to map an object
obj={a:'',b:firstname,c:'',d:lastname}
while mapping if an element of an object does contain : '', i will return to to null so the result will be like that :
obj={a:null,b:firstname,c:null,d:lastname}.
How can I do that?
You can use Object.keys to get an array of all the property names in the object, and then use reduce to build up a new object where all properties with value '' get the value null instead.
const obj = { a: "", b: "foo", c: "", d: "bar" };
const result = Object.keys(obj).reduce((acc, key) => {
acc[key] = obj[key] === '' ? null : obj[key];
return acc;
}, {});
console.log(result);
You can do this by using for in
var obj = {a:'',b:'firstname',c:'',d:'lastname'}
for(var key in obj){
if(obj[key] === ""){
obj[key] = null
}
}
console.log(obj)

es6 Loop through object array and aggregate unique values from key pair (cleanest way)

What's the cleanest and es6 native (if possible) way to loop through a object array to grab each unique value. Example would like this :
[{
"name" : "joe",
},
,{
"name" : "jean",
},
{
"name" : "joe",
},
{
"name" : "joe",
},
{
"name" : "mike",
}]
and in my results I want to see only : joe, jean, mike (only unique values, no dupes)
Since you mentioned ES6, it seems like a Set object would be what you want since it will do the uniqueness part for you and should do so fairly efficiently:
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
let uniqueNames = Array.from(new Set(objs.map(item => item.name)));
console.log(uniqueNames);
Run this snippet to see the results.
a = [{name:"joe"},{name:"jean"},{name:"joe"},{name:"joe"},{name:"mike"}]
console.log(_.uniq(_.map(a, 'name'))) // Lodash 0.1.0
console.log([...new Set(a.map(o => o.name))]) // ES6
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.4/lodash.min.js"></script>
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
var uniqueNames = objs.map( obj => obj.name )
.filter( (name, idx, arr) => { return arr.indexOf(name) === idx; } );
The .map extracts an array of the name values, and the .filter returns only the unique elements (first instances only).

How to fetch "name" property from an array if i know its corresponding "id"

I have a simple array with id and name. If i know the id then how can i fetch the name, array is shown below:
var dataobj = [
{id:1,name:"Jessica"},
{id:2,name:"Tom"},
{id:3,name:"Will"}
];
i have the id for example 2 with me in a variable, how can i get the name which belongs to this id ?
I have clickedID=2 value in my slist.component.ts and i want to fetch its corresponding name, how can i do it ?
To log the name which belongs to the id 2, it's as simple as following :
let obj = dataobj.find(obj => obj.id === 2);
console.log(obj.name);
you can use es6 array syntax:
dataobj.find(el => el.id === 2)
output:
Object {id: 2, name: "Tom"}
You can use the array find method
const secondItem = dataObj.find(function (item){
return item.id === 2;
})
Then name can be accessed as
secondItem.name
You can do something more readable and reusable with a dynamic find
var dataobj = [
{id:1,name:"Jessica"},
{id:2,name:"Tom"},
{id:3,name:"Will"}
];
let getNameFromObjId = obj => id => obj.find(x=> x.id===id).name;
console.log(getNameFromObjId(dataobj)(2))

Resources