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>;
});
Related
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);
I would like to combine elements of 2 arrays based on the name. For example:
Array1 = [
{name: "name1", language: "lang1"},
{name: "name2", language: "lang2"},
{name: "name3", language: "lang3"}]
Array2 = [
{name: "name1", subject: "sub1"},
{name: "name2", subject: "sub2"},
{name: "name3", subject: "sub3"}]
I need to generate the following array:
Array3 = [
{language: "lang1", subject: "sub1"},
{language: "lang2", subject: "sub2"},
{language: "lang3", subject: "sub3"}]
The logic I could think of was to write an explicit for loop to compare every element of first array with every element of second array and check if name matches as shown below.
let Array3 = []
for(let i=0;i<Array1.length;i++)
{
let elem = Array1[i];
for(let j=0;j<Array2.length;j++)
{
if(Array2[j].name===elem.name)
{
Array3.append({language: elem.language, subject: Array2[j].subject})
break;
}
}
}
However, my actual dataset is quite large and this seems inefficient. How can this can be achieved in a more efficient manner (like using higher order functions or something)?
Using a Map for O(1) lookup of one of the arrays using name as key lets you iterate each array only once.
const Array1=[{name:"name1",language:"lang1"},{name:"name2",language:"lang2"},{name:"name3",language:"lang3"}],Array2=[{name:"name1",subject:"sub1"},{name:"name2",subject:"sub2"},{name:"name3",subject:"sub3"}];
const a1Map = new Map(Array1.map(({name, ...r})=> [name, {...r}]));
const res = Array2.map(({name, ...r}) => ({...r, ...a1Map.get(name)}))
console.log(res)
You need to iterate over the two arrays and group the generated object in a map having the name as the key:
let Array1 = [
{name: "name1", language: "lang1"},
{name: "name2", language: "lang2"},
{name: "name3", language: "lang3"}
];
let Array2 = [
{name: "name1", subject: "sub1"},
{name: "name2", subject: "sub2"},
{name: "name3", subject: "sub3"}
];
let map = new Map();
Array1.forEach(e => map.set(e.name, {language: e.language}));
Array2.forEach(e => {
if(map.has(e.name))
map.set(e.name, {...map.get(e.name), subject: e.subject});
});
let Array3 = [...map.values()].filter(e => e.language && e.subject);
console.log(Array3);
Yes you are thinking in right order , you need to use the sort algorithm logics , I will say nested for loops will be just as good. With larger dataset , since you need to extract the values from two different array you can use the nested for loops.
for(int i=0;i>array1.length();i++){
This can be use for first array
Define String x=",";
For second
for(int j=0;j>array2.length();j++)
{
Check if ( (","+j+",").contains(x)) then break;
If array1 name found in array 2, store array3 as you want
Also Store value of j in x
Like x=x +j+",";
}}
This way your nested for loop will skip the comparison code.
Above algo is raw but will reduce the complexity a significant bit.
var arrNewMarket=[];
var arrMarket=[
{id:1,country:"India",city:"city1",fruit:"Red Apple",year:2019,jan:220,feb:300},
{id:2,country:"India",city:"city1",fruit:"Green Apple",year:2019,jan:777,feb:555},
{id:3,country:"India",city:"city2",fruit:"Red Apple",year:2019,jan:333,feb:888},
]
console.log(arrMarket);
for (let i = 0; i < arrMarket.length-1; i++) {
for (let j = i+1; j < arrMarket.length; j++)
{
if(arrMarket[i].country==arrMarket[j].country && arrMarket[i].city==arrMarket[j].city) {
arrNewMarket.push({
id:4,
country:arrMarket[i].country,
city:arrMarket[i].city,
fruit:"Apple",
year:arrMarket[i].year,
jan:arrMarket[i].jan/arrMarket[j].jan,
feb:arrMarket[i].feb/arrMarket[j].feb,
});
}
}
}
I have an array of multiple objects.
var arrMarket=[];
[
{id:1,country:India,city:city1,year:2019,jan:220,feb:300},
{id:2,country:India,city:city1,year:2019,jan:777,feb:555},
]
Can we create new object based on conditions
for eg:
if country matches and city matches then some "Divide" calculation for Jan and Feb and we can have 3rd object?
Any Suggestion and help will be appreciated.
[
{id:1,country:India,city:city1,year:2019,jan:220,feb:300},
{id:2,country:India,city:city1,year:2019,jan:777,feb:555},
{id:3,country:India,city:city1,year:2019,jan:0.28,feb:0.54},
]
You could use lodash filter.
It will allow you to pick out all of the objects in the array that meet the condition.
import filter from 'lodash/filter'
const array = [
{id:1,country: "India", city:"city1", year:2019, jan:220, feb:300},
{id:2,country: "India", city:"city1", year:2019, jan:777, feb:555},
{id:3,country: "UK", city:"city2", year:2019, jan:1, feb:12},
]
// gives you a list of all objects that match you conditions.
const filteredArray = filter(array, {country: "India", city: "city1"})
// make a new object with whatever math you wanted to do.
const newObject = {id: array.length, country: "India", city: "city1", year: 2019, jan: filteredArray.map(**some calculation**),feb: filteredArray.map(**some calculation**)}
// to ad it back to the original array of objects
array.push(newObject)
Hope that gives you somewhere to start.
I have a declaration in a code i received to program a logic for. I have already figured out my algorithm, but i'm unable to figure out what datatype this is. I basically have to compare values of "skills" of every row to 'JavaScript' and if it is true i need to do a task. I'm unable to access the value of skills. What datatype is this declaration and how do I access it's values?
I have tried accessing the values using row/column of table type and also using arrays, but nothing works. For adding/removing rows to this table,
const newCandidates = [
{ name: "Kerrie", skills: ["JavaScript", "Docker", "Ruby"] },
{ name: "Mario", skills: ["Python", "AWS"] }
];
You have an array of dictionaries. You can access its items like this:
const newCandidates = [{
name: "Kerrie",
skills: ["JavaScript", "Docker", "Ruby"]
},
{
name: "Mario",
skills: ["Python", "AWS"]
}
];
console.log(newCandidates[0].skills[1])
console.log(newCandidates[1].name)
It is array in javascript. Though javascript arrays are nothing but objects.
const newCandidates = [
{ name: "Kerrie", skills: ["JavaScript", "Docker", "Ruby"] },
{ name: "Mario", skills: ["Python", "AWS"] }
];
console.log("DataType of newCandidates: ", typeof newCandidates); // prints object type
// accessing skills array in newCandidates
for(var i = 0; i < newCandidates.length; i++) {
let person = newCandidates[i];
console.log("personName: ", person["name"]);
// since skills is array, iterate through it.
for(var j = 0; j < person["skills"].length; j++) {
let currentSkill = person["skills"][j];
// do something with currentSkill
console.log("Skill-" + j + " : " + currentSkill);
}
}
You have an array of Javascript objects(everything in curly brackets). Do a forEach loop on the array:
newCandidates.forEach(e => console.log(e.skills))
This will give you the skills array. You can use additional array methods to test whether the skills contain "Javascript"
newCandidates.forEach(candidate => {
if(candidate.skills.includes("Javascript") {
*execute your function*
}
}
I want to create an object with an array property which looks like this:
var arrayOfUsers = {
id: "some user id",
username : "some names",
roles : [array with roles]
}
And i would like to access an element by id, something like, arrayOfUsers['some id']['roles'];
I am new to json. I've tried different ways, but always ended up with bunch of errors.
First, this is a JavaScript object. JSON is a string representation of JavaScript objects.
Second, it's important to know the difference between an object and an array. In general, consider Objects to be defined with curly braces { } and Arrays with braces [ ]
Values in Arrays are accessed by their index with the arr[index] syntax while objects use obj[key] syntax to access the value assigned to some key on the object.
For your scenario, I'd avoid using arrays, because you want to be able to access objects by key, not by index.
var users = {
"some user id": {
username : "some names",
roles : {
"some role id": {
name: "role name"
}
}
}
};
In reality, this isn't a very effective data structure, because you'd likely want to deal with arrays for looping, rendering, etc, but to answer your question about being able to index by the Id of user and role, this is how your data would have to be structured.
Here is how you declare:
var currentUser,
currentRole,
arrayOfUsers = {
id: 1,
username: "Sample Value",
roles: [{
roleId: 1,
name: "Admin"
},
{
roleId: 2,
name: "Cashier"
}]
};
This is how you access it:
for (var i = arrayOfUsers.length; i--;) {
currentUser = arrayOfUsers[i];
for (var x = currentUser.roles.length; x--;) {
currentRole = currentUser.roles[x];
console.log("ID=" + currentRole.id + "Name=" + currentRole.name);
}
}
First, you have to make difference between array which defined by [], and Objects, by {}.
If you want to make an array of JSON, you can do the following :
var arrayRoles = [{
idRole: 1,
type: 'admin'
}, {
idRole: 2,
type: 'user'
}];
var userArray = [{
id: 1,
username: 'toto',
roles: arrayRoles
}, {
id: 2,
username: 'titi',
roles: arrayRoles
}, {
id: 3,
username: 'toto',
roles: arrayRoles
}];
Then, if you want to iterate over all your data, you can do it by using forEach loop, which tends to be more elegant :
userArray.forEach(function(elm){
//Our roles array
var roles = elm.roles;
//For all item in roles array
roles.forEach(function(value){
//display type of role, for example.
console.log(value.type);
});
});
But if you want to search a specific item in your JSON array, you can use filter method, by using high order function.
function filterBy(key, filter){
return function(elm){
return elm[key] === filter;
}
}
Then, you can apply this function to your filter, by passing specific field and value, and it will return an array of results :
var filtered = userArray.filter(filterBy('username', 'toto'));
//Display '1'
console.log(filtered[0].id);
//Display '3'
console.log(filtered[1].id);