convert an array of objects to one object of objects - javascript

How to convert an array of objects to one object of objects. My function works but I don't want key name before each object.
myArray = [{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}]
let result = {};
for (let item of seriesTotal) {
result[item.name] = item;
delete item.name;
}
I'd like this
myObject = {{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}{

An object is a collection of properties, and a property is an association between a name (or key) and a value.
You can use the index as the key or property name. Use Object.assign to create a new object. Use map and spread syntax to loop thru the array.
let myArray = [{
"name": "ann",
"y": 191,
"color": "red"
}, {
"name": "mary",
"y": 11,
"color": "red"
}, {
"name": "henry",
"y": 11,
"color": "red"
}];
let result = Object.assign(...myArray.map((o,i) => ({[i]: o})));
console.log(result);
Doc: Objects

Since what you want is not valid JS object, you'll get an string in JS, so you could use .replace():
myArray = JSON.stringify(myArray).replace(/(\[)(.+)(\])/g,"{$2}");
console.log(myArray);
//{{"name":"ann","y":191,"color":"red"},{"name":"mary","y":11,"color":"red"},{"name":"henry","y":11,"color":"red"}}
But as I said before, that is not a JS object, it's just a string.

Related

Console log the value of item in array

I have this array and I want to console log item value. How can I do that? I got this array from MongoDB. I would appreciate any help.
{
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}
Edit:
I looked in MongoDB documentation and found the solution. Thanks to everyone who answered.
I think you can simply access the key from the object like this:
const obj = {
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}
console.log(obj.item);
Another way could be to find out the keys and iterate over them if keys are dynamic in nature:
const obj = {
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}
const keys = Object.keys(obj);
keys.forEach(key => console.log(`Key is ${key} and the value is ${JSON.stringify(obj[key])}`))
You can try:
Object.entries(YOUR_OBJECT_NAME).filter(val=>val[0] === "item")
You will get back an array of key and value pair. You can then console.log your value.
Easier solution is that you directly determine your key. If you know what is the name of your key then you can do:
console.log(YOUR_OBJECT_NAME.item)

combining two arrays that have the same field in node js

I have arrays like these
arr1 = [{
"_id": 1,
"item": "Pencil",
"color": "Red"
},{
"_id":2,
"item": "Pen",
"color": "Yellow"
},{
"_id": 3,
"item": "Pencil",
"color": "Green"
}]
arr2 = [{
"value":"Pencil",
"price":1000,
},{
"value":"Pen",
"price":1500,
}]
How do I combine this arr2 into arr1 with "value" in arr2 and "price" in arr1 as the key? so that it has the following results
res = [{
"_id": 1,
"item": "Pencil",
"color": "Red",
"price": 1000
},{
"_id":2,
"item": "Pen",
"color": "Yellow",
"price": 1500
},{
"_id": 3,
"item": "Pencil",
"color": "Green",
"price": 1000
}]
You can use map. For example:
let arr3 = arr1.map((el1) => {
let found = arr2.find(el2 => el1.item == el2.value)
if (found)
el1.price = found.price
return el1
})
console.log(arr3)
You can use Map collection to have O(1) while mapping the second array:
const uniquePencils = new Map(arr2.map(s => [s.value, s.price]));
const result = arr1.map(a => ({...a, price: uniquePencils.get(a.item)}));
As mdn says about Map collection:
The Map object holds key-value pairs and remembers the original
insertion order of the keys.
So to create a map collection from array we can use map method:
const uniquePencils = new Map(arr2.map(s => [s.value, s.price]));
Then when we map array, we need to give item name(e.g. Pencil) to Map collection to get object from map collection.
arr1.map(a => ({...a, price: uniquePencils.get(a.item)}));
In addition, we've used ... operator. It is called spread syntax. It copies own enumerable properties from a provided object onto a new object.
An example:
let arr1 = [{
"_id": 1,
"item": "Pencil",
"color": "Red"
},{
"_id":2,
"item": "Pen",
"color": "Yellow"
},{
"_id": 3,
"item": "Pencil",
"color": "Green"
}];
let arr2 = [{
"value":"Pencil",
"price":1000,
},{
"value":"Pen",
"price":1500,
}];
const uniquePencils = new Map(arr2.map(s => [s.value, s.price]));
const result = arr1.map(a => ({...a, price: uniquePencils.get(a.item)}));
console.log(result);

Adding key in an array by finding a value AngularJS

I am trying to add an extra key in a JSON array by searching any key value.
Example JSON:-
[
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO"
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
Suppose I have to add a new key pair example "Price": 50 after "Name": "MANGO" or by finding ID ID": 45. So my expected new JSON will be :-
[
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO",
"Price": 50
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
It must add on the object related to matched search key.
So, I am not able to find out any function related to the issue.
You can run a loop and check the condition and then add a property to an object. Here is a running code snippet. You can read here more about JavaScript Objects
var myarray = [
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO"
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
for(var i=0;i<myarray.length;i++){
if(myarray[i].$id === "2025" || myarray[i].Name === "APPLE"){
var data = myarray[i];
data.price = 50
}
}
console.log(myarray)
You can use array#find to compare the ID. Then based that you can add Price key to the object.
let arr = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ],
id = 45,
obj = arr.find(({ID}) => ID === id);
if(obj);
obj.Price = 50;
console.log(arr);
You can try with:
data.find(item => item.ID === 45).price = 50;
To cover the case if item is not available:
(data.find(item => item.ID === 45) || {}).price = 50;

Filter and sort JSON formatted object?

Lets say I've got an object in JSON format (like below) and I want to sort it by UserID
oUserColors = { "users": [
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Red" },
{ "UserID": 32, "Color": "Green" },
{ "UserID": 30, "Color": "Green" },
{ "UserID": 32, "Color": "Red" }
] };
I can easily use the following function to do so.
objSortedUserColors = oUserColors.users.sort(function (a, b) {
return b.UserID - a.UserID; // sort oUserColors.users in descending order.
});
which would give me this...
objSortedUserColors = { "users": [
{ "UserID": 32, "Color": "Red" },
{ "UserID": 32, "Color": "Green" },
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Red" },
{ "UserID": 30, "Color": "Green" }
] };
But what if I want to also filter the object by color such that, if a user has both red and green as their color, the red gets removed and only the green remains. But if the user only has red as their color, it stays. Resulting in something like this...
objFilteredSortedUserColors = { "users": [
{ "UserID": 32, "Color": "Green" },
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Green" }
] };
I'm stuck. Any suggestions would be greatly appreciated!
As you know how to sort the array, I will just focus on the filter. You can use reduce for that and a helper object to maintain values keyed by UserUD. A Map would also work, but plain objects have an advantage of producing values in the order of increasing keys when they are non-negative integers.
const oUserColors = { "users": [{ "UserID": 31, "Color": "Red" },{ "UserID": 30, "Color": "Red" },{ "UserID": 32, "Color": "Green" },{ "UserID": 30, "Color": "Green" },{ "UserID": 32, "Color": "Red" }]};
const result = Object.values(oUserColors.users.reduce( (acc, obj) => {
const prev = acc[obj.UserID];
if (!prev || prev.Color === 'Red') {
acc[obj.UserID] = obj;
}
return acc;
}, {}));
console.log(result);
The idea is to build an object (acc) with only the values of interest, keyed by UserID. If you find that during this collection there is no value yet for a UserID, you add it. If there is a value, and it has colour Red, then it is safe to replace it with the current object.
With Object.values() you convert that object back to an Array.
As it happens that JavaScript in all common browsers will produce the values in order of numerical key order (if non-negative integers), the output will be sorted.

JSON remove key value for particular key name

I have a JSON like the following, I am trying to remove "age" from it and rename "name" to "key" and "height" to "value". Can someone please suggest what would be the neatest way to achieve this.
{
"data": [
{
"name": "A",
"age": 8,
"height": 120
},
{
"name": "B",
"age": 18,
"height": 150
}
]
}
Here is how you do it using map as I mentioned.
map is exactly what you're looking for, it's a way to create a new array based on an existing array using whatever criteria you want.
var json = {
"data": [{
"name": "A",
"age": 8,
"height": 120
}, {
"name": "B",
"age": 18,
"height": 150
}]
};
json.data = json.data.map(function (d) {
return {
key: d.name,
value: d.height
};
});

Categories

Resources