Finding the object key with the value inside the array? - javascript

I know Some people might find this very easy. But It seems to be very difficult to start. If i have array i could have easily done with filter.
Lets say i have this object
const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
Now if I have atribute = "gender" How can i find the key family.
if I have atribute = "livingType" Then i need House;
Any Javascript pro here?
Thanks in advance

You could get the keys and find with includes.
Methods:
Object.keys for getting own keys from an object,
Array#find for finding an item with a callback,
Array#includes, this checks if an item exists in an array.
const
mapData = { family: ["gender", "ethnics"], house: ["wardNumber", "livingType"] },
attribute = "gender",
key = Object
.keys(mapData)
.find(k => mapData[k].includes(attribute));
console.log(key);

You can use Object.keys() and filter()
const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
const findKey = (obj,attr) => Object.keys(obj).filter(k => obj[k].includes(attr))[0]
console.log(findKey(mapData,"gender"))
console.log(findKey(mapData,"livingType"))

You can do it with Object.entries(), Array.find(), Array.includes() and Array.shift().
If the value is not found, this will return undefined.
const data = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
const getKey = val =>
(Object.entries(data).find(([k, v]) => v.includes(val)) || []).shift();
console.log(getKey('gender'));
console.log(getKey('livingType'));
console.log(getKey('non-existing-value'));

Related

how can i check if an array of objects contains a key which is in array of strings js?

We have an array of objects like
const arr = [{id: "someId", name: {...}}, ...];
const skippedKeys = ["id"...]
How can i filtered the array of object based on skipped keys?
The result should be:
const result = [{name: {...}}, ...];
Also i don't want to make a cycle inside the cycle.
the result also could be implemented using lodash library.
we should remove key with value as well.
Since you stated that it could be implemented using lodash, here is some code using lodash:
let result = _.map(arr, (el)=> _.omit(el, skippedKeys))
const result = arr.map(obj =>
Object.keys(obj).reduce(
(res, key) => (
skippedKeys.includes(key) ? res : {...res, [key]: obj[key]}
),
{},
));
It's simple and no need for any nested cycles. There are two option to do that
Using includes function
const result = arr.filter((item) => !result.includes(item.id));
Using set
const dataSet = new Set(skippedKeys);
const result = arr.filter((item) => !dataSet.has(item.id));
I prefer the second one as it excludes double checks. Hope the answer was helpful.

How to replace array of object property name in javascript

I need to replace array of object in javascript. Here is my data variable and I want to update data variable
const data = [{name: "poran", id: "22"}];
Expected value:
data = [{value: "poran", age: "22"}];
How can I replace array of object?
You can create a new array with the use of .map() and some Object Destructuring:
const data = [{name:"poran",id:"22"}];
const result = data.map(({ name:value , id:age }) => ({value, age}));
console.log(result);
You can use a .forEach() loop over the array:
data.forEach((obj) {
obj.value = obj.name;
obj.age = obj.id;
delete obj.name;
delete obj.id;
});
It's a little simpler if you just make a new array with .map(), but if you need to keep the old objects because there are lots of other properties, this would probably be a little less messy.
try this:
const data = [{name:"poran",id:"22"}]
const rst = data.map(res=>({value: res.name, age: res.id}));
console.log(rst)

How to get the name from the array in javascript?

I am fairly new to JavaScript and I am trying to extract the name Sam from the array. The output that I'm getting is name. How do I get Sam? Thank you in advance. I apologize but I know this is a fairly novice question.
I am trying to loop by using forEach.
let Person = {
name: ['Sam']
}
let handler = Object.keys(Person)
handler.forEach(function(element){
console.log(element)
})
Object.keys() only gives you keys
Use Object.entries() if you want key and value
Use Object.values() if you only want values
let Person = {
name: ['Sam']
}
for (const fn of ["values", "keys", "entries"]) {
console.log(`Using: Object.${fn}()`);
for (const v of Object[fn](Person)) {
console.log(v);
}
}
Instead of Object.keys use Object.values
If you know in advance that your name array is located under the key name, then access it directly
const person = { name: ['Sam'] };
console.log(person.name);
console.log(person.name[0]);
Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for:
const person = { name: ['Sam'], anotherProp: 'hello' };
console.log(Object.values(person));
Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly.
let Person = {
name: ['Sam',"Bob","Alice"]
}
let count = Person.name.length;
for(let i = 0; i<count; i++){
console.log( Person.name[i])
}
If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation.
Object.keys(obj).forEach(key => obj[key]);
let Person = {
name: ['Sam']
}
Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`));

How to do multiple let in for loop

Can I assign 2 let in for loop? I tried this but gives me warning k[ts] ')' expected.:
for(let key in app.date let key2 in app.date2) {
data_series.push({
"year": app.date[key]._id,
"italy": app.date[key].count,
"germany": app.date2[key2].count2,
});
}
What is the correct syntax?
Assuming that both objects have the same number of keys, in order to iterate over both at once, you'd have to first construct an object of some sort that contains key pairs. But, from your code, it looks like you're interested only in the value at that key, not the key itself - if what you want is clear, short code, you might use an array method instead: iterate over the Object.values of app.date, and use the index to access the appropriate value inside date2:
const date2Values = Object.values(app.date2);
Object.values(app.date).forEach(({ _id, count }, i) => {
data_series.push({
year: _id,
italy: count,
germany: date2Values[i].count2
});
});
If you had to use for, then construct an object of key pairs beforehand, and iterate with for..of:
const date2Keys = Object.keys(app.date2);
const allKeys = Object.keys(app.date)
.map((key, i) => ({ key, key2: date2Keys[i] }));
for (const { key, key2 } of allKeys) {
// etc
}
or, it might be clearer with a plain for loop instead:
const dateKeys = Object.keys(app.date);
const date2Keys = Object.keys(app.date2);
for (let i = 0, { length } + Object.keys(app.date); i < length; i++) {
const key = dateKeys[i];
const key2 = date2Keys[i];
// etc
}
But the Object.values version is probably preferable, since it's more abstract, functional, and doesn't require manual iteration.
Also, if data_series is an empty array beforehand, it would be more appropriate to use .map than to use forEach and push:
const date2Values = Object.values(app.date2);
const data_series = Object.values(app.date).map(({ _id, count }, i) => ({
year: _id,
italy: count,
germany: date2Values[i].count2
});
If at all possible, I'd recommend changing your data structure so that each item of date and date2 is clearly associated with the other, such as an array, rather than depending on each object happening to have the same ordered property names. Although property order is guaranteed in modern browsers, it's not a good thing for code to depend on.

Convert array of objects to plain object using Ramda

How can I convert an array of objects to a plain object?
Where each item of the array is an object with only one key:value pair and the key have an unknown name.
I have this
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas' }
]
let result = {}
const each = R.forEach((item) => {
const key = R.keys(item)[0]
result[key] = item[key]
})
return result
But I dislike that solution because the forEach is using a global variable result and I'm not sure how to avoid side effects here.
Ramda has a function built-in for this, mergeAll.
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
R.mergeAll(arrayOfObject);
//=> {"KEY_A": "asfas", "KEY_B": "asas"}
Since everybody is using ES6 already (const), there is a nice pure ES6 solution:
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas'}
];
Object.assign({}, ...arrayOfObject);
//=> {KEY_A: "asfas", KEY_B: "asas"}
Object.assing merges provided objects to the first one, ... is used to expand an array to the list of parameters.
Use reduce instead:
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
const each = R.reduce((acc,value) => {
const key = R.keys(value)[0];
acc[key] = value[key];
return acc;
},{},arrayOfObject);
Since your array is an array of objects, you could also just call merge inside a reduce:
const each2 = R.reduce((acc,value) => R.merge(value,acc),{},arrayOfObject);
Here is a jsbin with both examples:
http://jsbin.com/mifohakeru/edit?js,console,output

Categories