How to check if array contains objects - javascript

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.

Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}

(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

Related

Puh array in empty array that create before

I push two Array in one Array But can't use them as a string,This result in bellow about two arrays in one array :
Array(0) [] //This is empty array that I create before and push these two array bellow to them
length:2
0:Array(1) ["cfdb9868-0f69-5781-b1e4-793301280788"]
1:Array(1) ["cfdb9868-0f69-5781-b1e4-793301280788"]
and I create a for for access them but I can ! I write this code "
for(var index = 0 ; index < Array.length ; ++index) {
let Each_String_In_Brackets = Array[index] ;
console.log(Each_String_In_Bruckets);
}
Why is this happen!
I mean Why when we push array in empty array can't access them!
I want to access the content of them, I have a string In each bracket.
var arr = [];
arr.push(["cfdb9868-0f69-5781-b1e4-793301280788"]);
arr.push(["cfdb9868-0f69-5781-b1e4-793301280788"]);
//assuming inside array always will be one element:
arr.forEach((item)=>{ console.log(item[0])})
//if inside array may be multiple elements, then use this
arr.forEach((item, index)=>{
item.forEach((child)=>{ console.log(child)})
})
pushing a full array into another array makes it a 2D array ( at the indexes where you push another array ) so for example if I have the first array
BArray[]
But if I push another array into it
BArray2 = [1,2,3,4];
BArray.push(Array2);
We would not be able to access it just by
BArray[0]
This would return the entire array2 rather the content of array2 at index 0.
Therefore you would do this
BArray[0][0]
So this would give us ( from your array ) "cfdb9868-0f69-5781-b1e4-793301280788"
If you would like to just dump out the content of BArray2 into BArray
You can use the spread operator.
BArray[...BArray2];
( Also I would not use Array as variable name ! It can be confusing as new Array(10); is a way of creating arrays and having arrays with that name isn't best practice ! )
Hope this helps !
You are pushing array in array, so you must access as 2D array:
var array = [];
var arrayString1 = ["StringInArray1"],
arrayString2 = ["StringInArray2"];
array.push(arrayString1);
array.push(arrayString2);
console.log(JSON.stringify(array));
array.forEach(arrayItem => {
console.log("StringInArray: " + arrayItem[0]);
})
Or maybe you want to append array:
var array = [];
var arrayString1 = ["StringInArray1"],
arrayString2 = ["StringInArray2"];
[].push.apply(array, arrayString1);
[].push.apply(array, arrayString2);
console.log(JSON.stringify(array));
array.forEach(arrayItem => {
console.log("StringInArray: " + arrayItem);
})

Cannot get/fetch keys from an array in javascript

I have an array object where there are key value pairs. I am trying to get the keys in that array using a loop but I am getting only 0. What is the problem with my code.
var strj = '{"name":"John","age":"30","cars":
[ {"type":"car", "year":"1998"},
{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type=='car');
Value of care
0:{type: "car", year: "1998"}
length:1
__proto__:Array(0)
Loop
for (var key in care){
if(care.hasOwnProperty(key)){
console.log(key)
}
}
care is a array type so you cannot do for (var key in care). You need to do for (var key in care[0]). This is because for (var key in care) will look for the key value in care and since it is a array it will always take 0 as a value in key(as you have only one object in array and its index is 0). That is why you got 0 in console.log.
var care =[{type: "car", year: "1998"}];
for (var key in care[0]){
if(care[0].hasOwnProperty(key)){
console.log(key)
}
}
care.forEach( ( singleCar ) => {
for ( var key in singleCar ){
console.log(key);
if( care.hasOwnProperty( key ) ){
console.log(key);
}
}
})
forEach will give you all the objects one by one. so you can check them.
As others have solved the issue, might i make a suggestion - Object.keys () gives an array of the keys for a given object. Since you are getting your filtered object and simply want its keys - the following will achieve that. Note that this is only using the code after you have filtered the original and have gained the "care" object.
As an aside, note that object.values() will give you an array of the values in a given object and object.entries() will give you arrays of the key / value pairing.
var care = {type: "car", year: "1998"};
var keys = Object.keys(care)
console.log(keys) // gives ["type","year"]
filter() method returns a Array of matches.
var care = myobj.cars.filter(c => c.type=='car'); // So, this returns an array.
care.forEach(element => {
console.log(Object.keys(element)); //Prints keys of each element
});
Well actually there is no problem in your code at all. But you just misunderstood the use of javascript filter. Javascript filter() creates new array that's why you are getting 0 as key. If you want to get only one matching element then find() is what you should use.
var strj = '{"name":"John","age":"30","cars":[{"type":"car", "year":"1998"},{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type == 'car'); // returns array
var care = myobj.cars.find(c => c.type == 'car'); // returns first matching object
var care = myobj.cars.findIndex(c => c.type == 'car'); // returns first matching index
Javascript filter() method => Read Here
Javascript find() => Read Here
Javascript findIndex() method => Read Here

How to do a basic javascript loop / accessing array data

I have been searching A LOT to find a simple way to loop through an array (I haven't used javascript much) and I just can't seem to make sense of the examples I've seen.
I also want to retrieve data from an array...
The following example I can understand:
https://www.w3schools.com/js/js_loop_for.asp
But it's just not useful for the use case I want it for.
Say I have an array that looks like this:
array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
Question 1: How can I access the first object in that array, i.e. where the 'key' = 1?
Question 2: How can I then loop through the "values" from this object?
e.g. In Python I would do something like:
get_first_object = array1[0]
for value in array1['values']:
print value
How can I do this kind of coding in javascript?
Edit
I didn't mention this properly
My "array1" is coming from a Python view and so the output of this is different to a standard JS array (see output of console.log below):
["[{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values':["two", "2"]}]"]
so when I do var object = array1[0] I get the following output:
[{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values': ["two", "2"]}]
It doesn't seem to be getting the first object but rather seeing the whole thing as one object.
Also
I require to get this dynamically - so I can't actually hard code "array1[0]" or "array1[1]" - How can I do this?
How I am defining the array
var array1 = ["{{ my_array_1|safe }}"];
Edit 2
The way I wish to get the object from the array is like so:
var selected_id = 1;
var selected_object = array[key=selected_id];
Let's assume that your array is this:
var array = [{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values': ["two", "2"]}];
This is an array which contains javascript objects, each with 2 properties, 'key', whose corresponding value is an integer and 'values' whose corresponding value is an array of data. If I understand this correctly, you want, given an integer input_id, to access the aforementioned array of data.
function access_data (id) {
for(let obj of array){
if(obj['key'] == id){
return obj['values'];
}
}
}
If you are familiar with python you probably recognize the for .... of syntax, since it's basically the same as python's for .... in. The above code assumes that your array is a global variable called array. Calling the function with an integer argument loops through every object your array contains, checks if its 'key' property matches the given id, and if it does, the corresponding array of data is returned.
More details on for ... of loops here
This self explanatory code should rectify your doubts
var array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}];
// First Object
var firstObject = array1[0];
console.log("First object", firstObject);
// Accessing key property of first object
var keyOfFirstObj = firstObject.key;
console.log("Key", keyOfFirstObj);
// Iterating through all the values of first object
Object.values(firstObject).forEach(
el => console.log("Value -- ", el)
)
You can hardcode it: array1[0].key // 1
Use forEach to loop over:
const array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
array1.forEach(arrItem => console.log(arrItem))
Or map over it if you intend to change datas as #str said below:
const array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
array1.map(arrayItem => console.log(arrayItem);
On mapvs forEach:
https://codeburst.io/javascript-map-vs-foreach-f38111822c0f
There are a few ways to do this, the basic for loop and the for..of loop
for
for (let i = 0; i < array1.length; i++) {
console.log(array1[i])
}
for..of
for (const val of array1) {
console.log(val)
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
if you want to select an object that has a key property of "1", you could loop through the array using the methods above, returung when that condition is true, or you could use Array#filter
const filtered = array1.filter(item => item['key'] === 1) //=> returns a new array
const myObj = filtered[0]
If you want a similar syntax to Python, you Coups use the for...in loop:
let get_first_object = array1[0];
for (let index in array1['values']){
console.log(array1['values'][index]);
}
Edit:
As for your edit, you need 2 loops
let objectArray= array1[0];
if(objectArray){
for(let outerIndex in objectArray){
for(let innerIndex in objectArray[outerIndex]['values']){
console.log(objectArray[outerIndex]['values'][innerIndex];
}
}
}
Edit:
let objectArray= array1[0];
if(objectArray){
let valuesObject=objectArray.filter(f=>f.key===selectedId);
for(let innerIndex in valuesObject['values']){
console.log(valuesObject ['values'][innerIndex];
}
}
}

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Categories

Resources