add key value pairs to object from an array - Javascript - javascript

How can I automate the process of assigning the key to an object from an array and the value to contain the same element as a string?
I have an empty object and an array:
const myObject= {};
const newsCategory = ['business', 'entertainment', 'general', 'health', 'science'];
I need to populate the object with key-value pairs.
The key should be each element from the newsCategory array.
The value should be an instance of another object.
new GetNews({country: 'gb', category: newsCategory[element]});
I can do this the manual way, assigning each category individually:
myObject.business = new GetNews({country: 'gb', category: newsCategory ['business']});
...and the same to the rest of the categories.
The result would be
{
business: GetNews {
category: "business"
country: "gb"
}
entertainment: GetNews {
category: "entertainment"
country: "gb"
}
general: GetNews {
category: "general"
country: "gb"
}
health: GetNews {
category: "health"
country: "gb"
}
science: GetNews {
category: "science"
country: "gb"
}
}
I need to do this process automatically, with a loop for example.
This is my attempt but it's not working.
newsCategory.forEach((category) => {
let cat = String.raw`${category}`; //to get the raw string
myObj.cat = new GetNews({country: 'gb', category: category});
})
};
/*
output:
{cat: "undefined[object Object][object Object][object Obj…ect][object Object][object Object][object Object]"}
*/
How can I automate the process of assigning the key to an object from an array and the value to contain the same element as a string?

Instead of myObj.cat you should do myObj[cat] so that cat is evaluated as the key value, otherwise you're setting a key named "cat".
Also String.raw is weird, don't use that. Your categories are strings already.
newsCategory.forEach((category) => {
myObj[category] = new GetNews({country: 'gb', category: category});
})
};

Related

How to filter few properties of an object which is in Array of objects if one property equals property from another object

I have a object which has some properties for one user, and I have array of objects which is returned from API.
My goal is to check which object of Array of objects has the same property as the one single initial object, and then it should return only part of it's properities.
I have tried to use .map on Array of objects but it seems not workig.
Below is the code example. I have also prepared codesandbox if You wish.
const user =
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
car: "audi"
}
;
const usersAnimal = [
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
animal: "cat",
animalSize: "small",
animalName: "Bat"
},
{
name: "john",
lastName: "smith",
fullName: "john smith",
animal: "dog",
animalSize: "middle",
animalName: "Jerry"
},
{
name: "Anna",
lastName: "Nilsson",
fullName: "Anna Nilsson",
animal: "cow",
animalSize: "big",
animalName: "Dorrie"
}
];
const filtered = usersAnimal.map((userAnimal)=>userAnimal.fullName === user.fullName && return userAnimal.animalName & userAnimal.animalSize & userAnimal.animal);
thanks
https://codesandbox.io/s/admiring-edison-qxff42?file=/src/App.js
For case like this, it would be far easier if you filter it out first then proceed using map:
const filtered = usersAnimal
.filter((animal) => animal.fullName === user.fullName)
.map(({ animalName, animalSize, animal }) => {
return {
animalName,
animalSize,
animal
};
});
I am providing a for loop solution as I haven't learnt many array methods in javascript.
For me the simplest option is to use a for loop and an if check to loop through the arrays values to check for included values.
for (let v in usersAnimal) {
if (usersAnimal[v].fullName === user.fullName) {
console.log(usersAnimal[v])
}
}
The code above will log the entire usersAnimal object containing the fullname we are looking for.
{
name: 'jan',
lastName: 'kowalski',
fullName: 'jan kowalski',
animal: 'cat',
animalSize: 'small',
animalName: 'Bat'
}
commented for further understanding
for (let v in usersAnimal) {
//loops though the array
if (usersAnimal[v].fullName === user.fullName) {
//when the index value 'v' has a fullname that matches the user fullname value
// it passes the if check and logs that object value
return console.log(usersAnimal[v])
//return true...
}
//return null
}
//etc
If you want to filter, I recommend you to use filter.
The map method will create a new array, the content of which is the set of results returned by each element of the original array after the callback function is operated
const user = {name:"jan",lastName:"kowalski",fullName:"jan kowalski",car:"audi"};
const usersAnimal = [{name:"jan",lastName:"kowalski",fullName:"jan kowalski",animal:"cat",animalSize:"small",animalName:"Bat"},{name:"john",lastName:"smith",fullName:"john smith",animal:"dog",animalSize:"middle",animalName:"Jerry"}];
// Get an array of matching objects
let filtered =
usersAnimal.filter(o => o.fullName === user.fullName);
// You get the filtered array, then you can get the required properties
filtered.forEach(o => {
console.log(
'animal:%s, animalSize:%s, animalName:%s',
o?.animal, o?.animalSize, o?.animalName
);
});
// Then use map to process each element
filtered = filtered.map(o => {
const {animal, animalSize, animalName} = o;
return {animal, animalSize, animalName};
});
console.log('filtered', filtered);

Constrain Table Search to Certain Dynamic Key Values in Javascript ArrayObjects

I am creating a custom search and I have an array of objects.
const data = [{
name: "Janet McKenly",
age: 49,
city: "Baltimore",
active: "2019-02-15",
role: "Admin. Assistant"
},
{
name: "Eric Brown",
age: 23,
city: "Dallas",
active: "2020-06-01",
role: "Janitor"
},
{
name: "Nora Payne",
age: 41,
city: "Los Angeles",
active: "2020-10-02",
role: "Sales Associate"
}
]
I have another array that is dynamically created that allows only for the specific parameters to search in.
let searchColumnOnlyArray = ["name", "city", "active"]; // (generated dynamically)
role & age should not be searchable.
The goal is to only search values for keys set in searchColumnOnlyArray.
I am able to filter by hardcoding a name parameter ["name"] but the searchColumnOnlyArray is dynamic and will change... below is the method I am using:
searchTable(term: any, data: any) {
let search = data.filter((indivitem: object) => {
if(indivitem["name"] === term) {
return indivitem;
}
}
console.log("searchResults", search);
}
I need advice on how to use my searchColumnOnlyArray to only search values in those keys. Advice on how I can constrain my filter to look/search values using the set keys in searchColumnOnlyArray?
You can use the .some() method for each individual item within your filter callback. With the .some() method, you can iterate through your columns array and return true when one of the given column values (ie: keys) holds a value which matches your search term. If your .some() callback never returns true, and false for every column item/key, then the result of calling .some() will be false, which will result in the filter method not keeping the item in the final resulting array:
const data = [ { name: "Janet McKenly", age: 49, city: "Baltimore", active: "2019-02-15", role: "Admin. Assistant" }, { name: "Eric Brown", age: 23, city: "Dallas", active: "2020-06-01", role: "Janitor" }, { name: "Nora Payne", age: 41, city: "Los Angeles", active: "2020-10-02", role: "Sales Associate" } ];
const searchColumnOnlyArray = ["name", "city", "active"];
const term = "Dallas";
const search = data.filter(item =>
searchColumnOnlyArray.some(col => item[col] === term)
);
console.log("searchResults", search);
Note: In your example, you are returning the item which you want to keep in the filter method, while this works, it's not how you should be using .filter(). Your callback should be returning true/false (or a truthy/falsy value). When you return true, the current item is kept in the resulting array returned by .filter(), if you return false then it is not kept in the resulting arrray.
data.forEach(ele => {
searchColumnOnlyArray.forEach( search => {
console.log(ele[search]);
});
});
I can't try the code right now but this should do the job

How to transform a nested array into string if it contains null values or just an empty one?

I need to replace nested arrays inside a main array that have null values like lets say [null, null] or the nested arrays that are empty with a string value like "empty".
Saying that we have the following array:
array = [
{
id: 123,
name: 'Peter',
phone: [null, null],
addresses: [{ address1: 'Manchester, UK', address2: 'London, UK' }]
},
{
id: 124,
name: 'Sara',
phone: [],
addresses: [{ address1: 'London, UK', address2: 'Paris, FR' }]
}
];
We see that, the first array has phone: [null, null] and the second has it as []. What I need to do it to transform them into the following:
array = [
{
id: 123,
name: 'Peter',
phone: "empty",
addresses: [{ address1: 'Manchester, UK', address2: 'London, UK' }]
},
{
id: 124,
name: 'Sara',
phone: "empty",
addresses: [{ address1: 'London, UK', address2: 'Paris, FR' }]
}
];
This is an example, and each array might contain multiple nested arrays that have the same [null, null] or [].
I tried the following:
var filtered = this.array.map(subarray => subarray.filter(el => el != null));
from this Stack Overflow answer, but I've got an error saying:
Error: subarray.filter is not a function
Then I tried a second method using lodash's every() and isNull method and property but couldn't figure it out:
let props = [];
props = Array.from(new Set(this.array.flatMap(e => Object.keys(e), [])));
console.log(props)
for (const prop of props) {
this.array.forEach(e => {
if ((Array.isArray(e[prop]) || typeof(e[prop]) === 'object') && e[prop]._.every(_.isNull)) {
console.log(e)
}
});
}
I searched few questions on Stack Overflow but the structure of the arrays are like: [ [1, 2], [1,3]...] and not like my array's structure [{...}, {...}], so I tried some of the solution and got the same error of method 1 above.
Here is a stackblitz.
First loop through the array, and within each object, you can set the phone property:
for(const entry of array) {
const isEmpty = entry.phone.filter(p => p !== null).length === 0;
entry.phone = isEmpty ? 'empty' : entry.phone;
}
Caveat is that this edits your array. One concern about the premise of the question is that you are setting an array property to a string, which is not ideal.
Live Example: https://jsfiddle.net/michaschwab/9ze3p2or/3/, and here's your edited stackblitz: https://stackblitz.com/edit/null-nested-array-into-string-jwhfwn
If you want to not modify your array, this is a way to do it:
const modified = array.map(entry => {
return {...entry, // Copy previous values
phone: entry.phone.filter(p => p !== null).length === 0 ? 'empty' : entry.phone
};
});
Map the array, and use _.mapValues() on each object. For each values that is an array, and full of null values, return 'empty':
const array = [{"id":123,"name":"Peter","phone":[null,null],"addresses":[{"address1":"Manchester, UK","address2":"London, UK"}]},{"id":124,"name":"Sara","phone":[],"addresses":[{"address1":"London, UK","address2":"Paris, FR"}]}];
const result = array.map(o =>
_.mapValues(o, v => // map the values of the object
_.isArray(v) && v.every(_.isNull) ? 'empty' : v // if a value is an array, and all values are null return 'empty'
)
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

How to add key value pair to the json?

I am fetching some json, but i want to add a key value pair to each object inside the array.
What i want is to add a key value pair to each object inside students array
You can do something like this:
var students = [ { city: 'California', company: 'ABC'}, { city: 'LA', company: 'PQR'}, { city: 'Mumbai', company: 'XYZ'}];
students.forEach((obj) => {
obj['email']= 'abc#xyz.com';
console.log(obj);
});
// Final Output
console.log(students);
I would suggest you simply use a for loop for each element in your array and since it's JSON simply specify a new "key = value" inside the current element.
edit : here's an example :
var entreprises = [
{id: 33, uuid: "3d103130-ae0d-11e9-8e6c-dfb1a3a5afce", nom: "test", adresse: "test", ville: "tes" },
{id: 34, uuid: "81524090-ae0d-11e9-8894-2326c7695f11", nom: "test2", adresse: "test2", ville: "test2"}];
for (let i = 0; i < entreprises.length; i++) {
entreprises[i].key = "value";
}
Start by iterating through the students array using either a foreach or standard for loop. This will give you access to each of the students, one by one. Since each of the students is an object, you will have to use either bracket or dot notation to store this new key,value pair. Here is an article that will help you determine which strategy to use for accessing keys and storing key,value pairs: Bracket notation vs Dot notation
Note: If the key you are adding already exists, you will be overriding the previous value.
For loop
for (let i = 0; i < students.length; i++) {
const student = students[i];
student[<key>] = <value>;
}
Foreach
students.forEach(student => {
student[<key>] = <value>;
});

JavaScript - New Nested Object From Current Object Keys

When working with an object like the following, what is the most effective way to build a new object based on the current object's keys? The keys serve as the reference to where it should be in the new object - activityName1 would be equal to the first element name of the new activities nested array, activityName2 equal to the second element name of the array & so on.
const obj = {
activityName1: "Bingo",
activityName2: "Bazinga",
activityType1: "Dog",
activityType2: "Term",
description: "Games are fun.",
name: "Patty"
};
Desired object:
const newObj = {
activities: [
{name: "Bingo", type: "Dog"},
{name: "Bazinga", type: "Term"}
],
description: "Games are fun.",
name: "Patty"
};
My initial thoughts were to use reduce & Object.assign, but the building of the new object returns only a single key/value pair:
Object.keys(variables).reduce((obj, key) => {
if (key.includes('activity')) {
return Object.assign(obj, {
[key[key.length - 1]]: { activities: { [key]: variables[key] } } });
}
return obj;
}, {});
Results in a new activities array like:
[
1: {activities: {type: "Dog"},
2: {activities: {type: "Term"}
]
The only use of mapping is to look for those keys that start activityName and use those to build up your array of activities. You can reuse the key replacing activityName with activityType to get the associated type.
const obj = {
activityName1: "Bingo",
activityName2: "Bazinga",
activityType1: "Dog",
activityType2: "Term",
description: "Games are fun.",
name: "Patty"
};
var result = {
activities: Object.keys(obj).filter(k => k.startsWith("activityName")).map(k => ({
name: obj[k],
type:obj[k.replace("activityName","activityType")]
})),
description: obj.description,
name: obj.name
}
console.log(result);

Categories