Appending key value pairs to an array in Javascript - javascript

I need an array of key value pairs. How do I append key value in an array inside a for loop.
array_of_countries = {};
country_data.features.forEach(each_country => {
array_of_countries.id = each_country.id;
array_of_countries.country_name = each_country.properties.name;
});
console.log("array of countries", array_of_countries)
This code only gives the last country id and name. I would like to know how to append values in this case. I get the answer as "push" but I am not sure how to use "push" for inserting a key and value. Please help !

{} is an object, not an array. An array is created by []. What you want to do is done using map
const countryData = {features: [{id: 1, properties: {name: 'Foo'}}, {id: 2, properties: {name: 'Bar'}}]};
const countries = countryData.features.map(({id, properties}) => ({id, name: properties.name}));
console.log(countries);

You do need Array.prototype.push for this. Also as you asked for a key-value pair, I assume you want the id to be the key and the properties.name to be the value.
let arrayOfCountries = [];
countryData.features.forEach(country => {
arrayOfCountries.push({
[country.id]: country.properties.name;
});
console.log(arrayOfCountries);

Related

How to check if values in array is present in object key of object array

I want to check if values in one array is present in object key of object array.
For example: arr = ["id1", "id2"]
objectArr = [{id: "id1"}]
I want to throw not found error in this case when id2 is not present in id of object array.
Help of any kind would be appreciated!
You can use filter and some for that:
var objectArr = [{id: "id1"}, {id: "id3"}]
var arr1 = ["id1", "id2"];
const notFounds = arr1.filter(el => !objectArr.some(obj => obj.id === el ));
console.log(notFounds); // ["id2"]
JS Array some:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
JS Array filter:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
If You iterate over objectArr, You can get object fields in form of array with: Object.entries(your_object).
for (const obj of objectArr) {
for (const item of Object.entries(obj)) {
// where item is field in object
// now You can compare if item is in [id1,id2]
}
}
You can try something like this
var arr = ["id1", "id2", "id3", "id4"];
var n = arr.includes("id2"); //true
For an array of objects. If the id is unique in the array
var arr = [{id:"id1"},{id:"id2"},{id:"id3"},{id:"id4"}]
const found = arr.some(el => el.id === "id3") // true
EDIT: ran.t has a better answer that keeps track of which ids are not found.
It sounds like what you're looking for is .every() method. Which will allow you can check each element in the array passes a given condition.
You can combine this with the .some() method to check at least one object in the objectArr has id equal to your element
const allElementsFound = ["id1", "id2"].every(el => objectArr.some(obj => obj.id === el))
if(!allElementsFound) {
// throw error
}

looking to remove duplicates from an array with key value pair

I have duplicate values looks like as shown in below figure
I have used below code but its only giving the names like as ashare1 guideline2and i am looking for id as well.
please find the below code currently i have used
const optionMap0 = [
...new Set(libraryEquipment.map(e => e.equipmentSource.name)),
{
id: '1d037be564c548eebe71db4e45e26cf7',
name: 'None',
},
];
Could any one please suggest any idea on how to get distinct values from the above array of objects.
many thanks in advance
You can convert it to an object, with the key as the name, and the value as the object itself, and then use Object.values() to get the objects.
const obj = {};
libraryEquipment.forEach(e => obj[e.equipmentSource.name] = e.equipmentSource);
const optionMap0 = Object.values(obj);
Unlike set, if you have more than one object with the same name, it will keep the last one. You can check before adding the object so it will use the first object with the same name, like so:
const obj = {};
libraryEquipment.forEach(e => {
if (!obj[e.equipmentSource.name])
obj[e.equipmentSource.name] = e.equipmentSource'
});
const optionMap0 = Object.values(obj);

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

Assign same key to values gotten from dynamic Array

I have an array received from backend: ["Drake","Ola","d"], now I need to assign all these values the same key which is id so it looks something like this:
[{id: "Drake"}, {id: "Ola"}, {id: "d"}]
I need a function to do this as the data is gotten after the page has loaded and I have tried many techniques including for loops.
I can also use JQuery if necessary, whats the solution please?
You could use Array#map and generate single objects with the wanted content.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var data = ["Drake","Ola","d"],
result = data.map(function (a) { return { id: a }; });
console.log(result);
ES6
var data = ["Drake","Ola","d"],
result = data.map(a => ({ id: a }));
console.log(result);
Map should do the trick. Just create an object for each value with the id property being that value.
var array = ["Drake","Ola","d"];
var newArray = array.map(function(value){
return {id: value}
})
console.log(newArray);

Convert Object to 2D array in JavaScript

Can we convert an Object to a 2D Array,
My Object is like this
So That Array Key will be like 'STARS_2' and value is ["STARS_4", "STARS_0", "STARS_12"]
with My attempts I can get something like this,
With this Code,
var testArray =[];
_.map(childFieldNames, function (value, key) {
var newArray = new Array();
newArray[key] = value;
testArray.push(newArray);
});
Here Keys are actually another array, which I do not want. I want key should be like 'STARS_2' , i.e. property of master object.
Is this what you need?
var ary2D = Object.keys(childFieldNames).map(function (key) {
return childFieldNames[key];
});
better version for what Shilly showed would be:
const arr2D = Object.values(childFieldNames);
Object.entries(obj)
E.g.
const objVariable = {name: "Ted", job: "Dentist"}
const 2dArray = Object.entries(objVariable)
console.log(2dArray) // will print [["name", "Ted"], ["job", "Dentist"]]
Object.entries is a static method that belongs to the Object class. As a parameter, it accepts an object and returns a two-dimensional array.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
You don’t need to create your structure into 2D array to just iterate over each key and its respective value(which is an array). If you want to iterate over it you can do something like this.
const object = {
a: [1,2,3],
b: [2,3,5]
};
for (const [key, value] of Object.entries(object)) {
value.forEach(v=>{
console.log(`${key}: ${v}`);
})
}

Categories

Resources