My JSON is:
"people": [
{
"id": "1",
"firstName": "John",
"lastName": "Smith"
},
{
"id": "2",
"firstName": "Ashton",
"lastName": "Negus"
},
{
"id": "3",
"firstName": "Roy",
"lastName": "Murrey"
}
]
I want to find where an item is by given value.
E.g. if I ask for id 1, I will get 0 because it's the first item in the array. If I ask for id 2, I will get 1 because that's the second item in the array, and so on.
Any help appreciated!
Use findIndex
var idToSearch = "1";
var index = people.findIndex( s => s.id == idToSearch );
Related
I am new to javascript usage.
I have a requirement to compare the field from two different array objects which are having list as below.
Array - A
[
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
]
Array - B
[
{
"element1" : "ert",
"id1":"iii",
"element2":"erws",
"element3":"234"
}
,
{
"element1" : "uio",
"id1":"xyz",
"element2":"puy",
"element3":"090"
}
]
The scenario is to compare for each 'id' in the list of array A, with the list of Array B to field 'id1'
Example -
I need to check from Array A -> 'id:xyz' matches the array B object field 'id1'.
Array A - id: xyz should match with id1: xyz in Array B
If the match occurs I need to pull out complete object from the array list A.
here id:xyz matches with id1:xyz
then pull out as below
[
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
}
]
Please help me with the suggestions to make this work using javascript.
const A = [
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
];
const B = [
{
"element1" : "ert",
"id1":"iii",
"element2":"erws",
"element3":"234"
},
{
"element1" : "uio",
"id1":"xyz",
"element2":"puy",
"element3":"090"
}
];
const C = A.filter(a => B.some(b => b.id1 === a.id));
console.log(C);
// the usage of `const` here means that arrA cannot be re-declared
// this is good for data that should not be changed
const arrA = [{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
];
const arrB = [{
"element1": "ert",
"id1": "iii",
"element2": "erws",
"element3": "234"
},
{
"element1": "uio",
"id1": "xyz",
"element2": "puy",
"element3": "090"
}
];
// slow method for long lists, fine for short lists or if there are duplicates
// compares each entry in array A to each entry in array B
const out1 = arrA.filter(x => arrB.some(y => x.id === y.id1));
console.log("Example 1: \n", out1);
// faster for long lists
// creates a set of unique values for array B's id1 parameter, ignores duplicates
// then checks that set for each entry in array A
const setB = arrB.reduce((a, b) => {
a.add(b.id1);
return a;
}, new Set());
const out2 = arrA.filter(x => setB.has(x.id));
console.log("Example 2: \n", out2)
.as-console-wrapper { min-height: 100% } /* this is just to make the stack overflow output prettier */
I have an array of objects being returned to me as data, I'm looking to Create a new set of data, while retaining the old one for future use.
I'm trying to loop through the data given to create a new set of data that only contains age, but also removes any duplicates. I'm not too sure where to start with this.
data = [
{
"firstName": "John",
"lastName": "Doe",
"age": "99"
},
{
"firstName": "Jimmy",
"lastName": "Hendricks",
"age": "50"
},
{
"firstName": "William",
"lastName": "Shakespeare",
"age": "22"
},
{
"firstName": "Jane",
"lastName": "Eyre",
"age": "50"
}
]
What I'd like to end up with is something like this:
newData = [
{"age": "99"},
{"age": "50"},
{"age": "22"}
]
Or you can just use Set for eliminating duplicates:
// ages variable contain just the ages
const ages = data.map(person => person.age);
// new Set(ages) will remove duplicated values:
const newSet = Array.from(new Set(ages)).map(age => ({ age: age }));
Wow, so many approaches!
Here is another one, purely functional:
data = [ { "firstName": "John", "lastName": "Doe", "age": "99" }, { "firstName": "Jimmy", "lastName": "Hendricks", "age": "50" }, { "firstName": "William", "lastName": "Shakespeare", "age": "22" }, { "firstName": "Jane", "lastName": "Eyre", "age": "50" } ];
console.log(
Object.keys(data.reduce((obj,o)=>
(obj[o.age]=1,obj),{}))
.map(k=>({age:k}))
)
let newData = [];
let uniques = [];
data.forEach(el => {
if(!uniques.includes(el.age)){
newData.push({age: el.age});
uniques.push(el.age);
}
});
You can use .map and .filter combined with a Set for this:
const data = [
{
"firstName": "John",
"lastName": "Doe",
"age": "99"
},
{
"firstName": "Jimmy",
"lastName": "Hendricks",
"age": "50"
},
{
"firstName": "William",
"lastName": "Shakespeare",
"age": "22"
},
{
"firstName": "Jane",
"lastName": "Eyre",
"age": "50"
}
]
const newdata = data
.map(({age}) => ({age})) // convert `{age: <value of age>}`
.filter(function({age}) {
const isUnique = !this.has(age); //check if already present
this.add(age); //add anyway
return isUnique; //filter keeping uniques
}, new Set());//use a Set as the `this` context for the filter
console.log(newdata);
I'm trying to find the intersection from 2 different arrays that contain slightly different objects.
For example:
const arr1 = [
{
"number":"1234",
"id":"34782",
"firstName":"John",
"lastName":"Smith",
"email":"test1#test.com",
},
{
"number":"1232",
"id":"34783",
"firstName":"Chad",
"lastName":"Baker",
"email":"test2#test.com",
}
];
const arr2 = [
{
"uuid":"0123",
"firstName":"John",
"lastName":"Smith",
"title":"Director"
},
{
"uuid":"0125",
"firstName":"Sam",
"lastName":"Hurst",
"title":"Manager"
}
]
const arr3 = arr1.filter(object => arr2.includes(object));
console.log(arr3);
I'm trying to create a new array that contains only the objects in arr1 where firstName and lastName values are the same in both arrays.
Desired result from above data:
arr3 = [
{
"number":"1234",
"id":"34782",
"firstName":"John",
"lastName":"Smith",
"email":"test1#test.com",
},
]
since this object's firstName and lastName match in both arr1 and arr2
Right now i have this.arr3 = this.arr1.filter(object => this.arr2.includes(object))
But because arr1 and arr2 contain different objects due to proper names, this doesn't work.
Try something like this:
const arr1 = [{
"number": "1234",
"id": "34782",
"firstName": "John",
"lastName": "Smith",
"email": "test1#test.com",
},
{
"number": "1232",
"id": "34783",
"firstName": "Chad",
"lastName": "Baker",
"email": "test2#test.com",
}
];
const arr2 = [{
"uuid": "0123",
"firstName": "John",
"lastName": "Smith",
"title": "Director"
},
{
"uuid": "0125",
"firstName": "Sam",
"lastName": "Hurst",
"title": "Manager"
}
]
const arr3 = arr1.filter(value =>
arr2.some(value2 =>
value.firstName === value2.firstName && value.lastName === value2.lastName
)
);
console.log(arr3);
Basically, use some instead of includes as this allows you to provide a predicate.
I think you can try this :
arr1.filter(item1 => (arr2.find(item2 => (item2.firstName == item1.firstName && item2.lastName == item1.lastName)) != undefined));
It uses the arr2.find function, to check if it contains some item with same firstName and lastName properties.
So say I have an array like so:
this.state = {
students: [{
"company": "This",
"firstName": "Randy",
"id": "1",
"lastName": "Orton",
},
{
"company": "That",
"firstName": "Clark",
"id": "2",
"lastName": "Kent",
}]
}
I would like to add an array to the first object so it looks like this.
this.state = {
students: [{
"company": "This",
"firstName": "Randy",
"id": "1",
"lastName": "Orton",
"array" : []
},
{
"company": "That",
"firstName": "Clark",
"id": "2",
"lastName": "Kent",
}]
}
How can I go about doing that without messing with initial state but only update it?
You can try to use these following ways:
this.state.students[0].array = [];
this.state.students.find(x => x.company === 'This').array = [];
After getting the response from server, you can add array property to each student object immediately:
Example:
var obj = {};
$.ajax({
type: 'POST',
url: '/yourAPIUrl'
}).done(function (response) {
obj.state = reponse;
for (var student of obj.state.students) {
student.array = [];
}
});
I have following JSON:
[ {
"id":1,
"firstName":"Markus",
"lastName":"Maier",
"email":"markus.maier#mail.de",
"externalId":"mmaie",
"company":"Intel"
},
{
"id":2,
"firstName":"Birgit",
"lastName":"Bauer",
"email":"birgit.bauer#mail.de",
"externalId":"bbaue"
} ]
I want to iterate through both objects and get the value of the "email" key.. what is the simplest way to do that? Thanks!
If you want to end up with an array of just the emails, you may want to look into the .map() function.
var data = [{
"id": 1,
"firstName": "Markus",
"lastName": "Maier",
"email": "markus.maier#mail.de",
"externalId": "mmaie",
"company": "Intel"
}, {
"id": 2,
"firstName": "Birgit",
"lastName": "Bauer",
"email": "birgit.bauer#mail.de",
"externalId": "bbaue"
}];
var emails = data.map(d => d.email);
console.log(emails);
Follow the code.loop through the data each object and for each object get the desired value by key.
var data = [ {
"id":1,
"firstName":"Markus",
"lastName":"Maier",
"email":"markus.maier#mail.de",
"externalId":"mmaie",
"company":"Intel"
},
{
"id":2,
"firstName":"Birgit",
"lastName":"Bauer",
"email":"birgit.bauer#mail.de",
"externalId":"bbaue"
} ];
for(var i=0; i< data.length;i++){
console.log(data[i]['email']);
}