Convert arrays to key value pair - javascript

I have an array
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
is it possible to become key value pair?
{
"flight1" : "123",
"flight2" : "456"
}

You can use reduce() and return object as result.
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)

The new Map() constructor can do this for you:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.
But if you prefer to have a plain object, you can get one this way:
var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));

You could map the key value pair and assign it to an object.
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);

you could use a standard for loop:-
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);

This might help someone another day. I tried all the examples above, but each time the console was giving me something like this:
{
flight1: "123",
flight2: "456"
}
My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
Note that flight1 and flight2 lost their double quotes. Below was my solution:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB: This was a code for submitting user information to a database (neDB) using the electron framework

Related

Merge objects of array having same value of a key but keep different values of another key as inner array [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
Closed 3 months ago.
I have an array which has keys eventId and selectedNumber. In the array same eventid can be present in multiple objects but selectedNumber value will be always different. My aim is to make a nested array in which each object will have unique eventId But selectedNumber will become an array having numbers from each of those objects having the same eventId. I tried using lodash _.groupBy() method but its just combines the objects into array and add it to the value with key as eventId. I don't want that. Anyway to do it?
Input:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
Result:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : ["20", "30"]
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
let newarr = []
oldArr.map((x,i)=>{
if(i==0){
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr newarr.push(x)
}else{
if(oldArr[i].eventId == oldArr[i-1].eventId){
const temp = x.selectedNumber
delete x.selectedNumber
newarr[i-1].numArr.push(temp)
}else{
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr
newarr.push(x)
}
}
})
Just reduce your input to an object, and map the object entries to the desired array format:
const input = [{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}];
const result = Object.entries(input.reduce((a, {eventId, selectedNumber}) => {
a[eventId] = a[eventId] || [];
a[eventId].push(selectedNumber)
return a;
}, {})).map(([eventId, selectedNumber]) => ({ eventId, selectedNumber }));
console.log(result);
Instead of creating the intermediate lookup object, you could directly reduce to an array, but it will have a negative impact on the solution's time complexity.

jQuery $.each - Iterate over an array of objects and select a field for each object

I have an array of objects like below, let's say arrayValues:
{ field1 : "933", field2 : "something", fieldN: "344" }
{ field1 : "21", field2 : "something", fieldN: "344" }
{ field1 : "34", field2 : "something", fieldN: "344" }
Using jQuery foreach I am trying to get value of field1 for each object in the array and then add them to another array, let's say newArray:
var newArray = [];
$.each(arrayValues, function () {
newArray.push('what to put here?');
});
At the end, newArray should contain: 933, 21, 34
How to do this?
You don't need jQuery for this. jQuery is a framework primarily for amending the DOM. For working with arrays you just need plain old Javascript. As such, simply using map() will build the array you require:
let arrayValues = [
{ field1 : "933", field2 : "something", fieldN: "344" },
{ field1 : "21", field2 : "something", fieldN: "344" },
{ field1 : "34", field2 : "something", fieldN: "344" }
]
let newArray = arrayValues.map(o => o.field1);
console.log(newArray);
Note that if you would prefer to have the values as integers use o => parseInt(o.field1, 10)
If, for whatever reason, you did want to do this in jQuery then you would use $.map():
let newArray = $.map(arrayValues, o => o.field1);
Consider the following code.
$(function() {
var arr = [{
field1: "933",
field2: "something",
fieldN: "344"
},
{
field1: "21",
field2: "something",
fieldN: "344"
},
{
field1: "34",
field2: "something",
fieldN: "344"
}
]
var newArr = [];
$.each(arr, function(k, v) {
newArr.push(parseInt(v.field1, 10));
});
console.log(newArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Please review: https://api.jquery.com/jquery.each/
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

acessing new object from Object.keys and forEach method javascript

I'm trying to create a new object (newobj) with new keys and props from a poorly structured existing array of object (arrays?) ex.
[{"product":["1009", "name", "price", "image", "description"]},
{"product":["1004", "name2", "price2", "image2", "description2"]}]
I'm getting result I want but newobj does not update outside of the scope of the forEach method (more than 1 result). My question is what am I not getting ? Is forEach incorrect method with this type obj?
var newobj = {};
Object.keys(oldobj).forEach(function(prop) {
newobj["id"] = Number(oldobj[prop]["product"][0]),
newobj["name"] = oldobj[prop]["product"][1],
newobj["price"] = Number(oldobj[prop]["product"][3]),
newobj["image"] = "url" + oldobj[prop]["product"][0] + ".jpg",
newobj["description"] = oldobj[prop]["product"][2];
// this works
// console.log(JSON.stringify(newobj));
});
// this only updated with one
app.locals.newobj = newobj;
I've also tried mapping (w/ underscore) but I have the same result, I can't access outside scope.
_.each(mappedobj, function(prop) {
_.each(prop["product"][0], function(vals){
newobj["id"] = Number(prop["product"][0]);
console.log(JSON.stringify(newobj));
});
});
If you want all the values from the old object, you need to make newobj an array of objects. You can use .map() to do this transformation.
Object and array destructuring is a convenient way to avoid all those hard-coded indexes. And by naming the parameter variables properly, you can use object literal shorthand to create the resulting objects more easily.
var oldobj = [{
"product": ["1009", "name", "price", "image", "description"]
},
{
"product": ["1004", "name2", "price2", "image2", "description2"]
}
];
var newobj = oldobj.map(({product: [id, name, price, url, description]}) =>
({id: Number(id), name, price: Number(price), url: `url${url}.jpg`, description})
);
console.log(newobj);
Try this
let newObject = _.map(oldObject, (item) => {
return {
id: item.product[0],
name: item.product[1],
price: item.product[2],
image: item.product[3],
description: item.product[4]
};
});
If you want to convert an array of poorly structured object to an array of well structured ones, you can use Array.prototype.map from VanillaJS:
const data = [
{"product": ["1009", "name", "120", "image", "description"]},
{"product": ["1004", "name2", "250", "image2", "description2"]},
{"product": ["1012", "name3", "85", "image3", "description3"]}
];
const products = data.map(({ product }) => {
const [id, name, price, image, description] = product;
return {
id: Number(id),
name,
price: Number(price),
image: `url${image}.jpg`,
description
};
});
console.log(products);

building an array object by pushing json

I have two objects as follows:
var id="one";
var arrobj = Array[2]
0: Object
name : "a"
desc : "desc1"
1: Object
name : "b"
desc : "desc2"
I am trying to build the object in the following format :
var secondobj = [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]
I tried this :
var secondobj= new Array();
var samplejson = {};
I just gave
samplejson.name = id;
After this I am a bit confused as in how to push values to get the above data structure.
It is a simple as:
samplejson[id]=arrobj;
var arrobj = [{
"name" : "a",
"desc" : "desc1"
},{
"name" : "b",
"desc" : "desc2"
}]
var secondobj = [];
secondobj.push({
one : arrobj
})
console.log(secondobj);
Check this jsfiddle for demo
To make the above structure you can try this:
var secondobj= new Array();
var samplejson = {};
samplejson.one = arrobj;
secondobj.push(samplejson);
console.log(secondobj) // this will give [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]

Extract a section of many objects in an array

If I have array of objects like this
[
{
"name" : "some name",
"more data" : "data",
...
},
{
"name" : "another name",
"more data" : "data",
...
},
...
]
And I want to copy the array, but only the name element in the object so that I have this:
[
{
"name" : "some name",
},
{
"name" : "another name",
},
...
]
Is there a short hand way to do this without writing a loop?
No, you have to do this with a loop, but in can still be short:
for(var i = 0; i < arr.length; i++)
arr[i] = {name: arr[i].name};
If you use any sort of framework or library all it will do is hide the loop from you. It will still loop through everything.
Example
No, there is no way of doing this without a loop. Can I suggest you do this with a bit of prototyping magic. (Note, this can be done with some map or forEach magic which just hides away the fact that you're looping. I'll leave this with the loop to illustrate the idea)
Array.prototype.clone = function(predicate)
{
var newArray = [];
for(var i = 0;i <this.length; i++){
var newElement = {};
for(x in this[i]){
if(predicate(x)){
newElement[x] = this[i][x];
}
}
newArray.push(newElement);
}
return newArray;
}
This allows you to clone an array, passing in a function that decides which property to keep from each element in the array. So given an array like:
var arr = [
{
"name" : "some name",
"more data" : "data"
},
{
"name" : "another name",
"more data" : "data"
}
];
You can do
var newArray = arr.clone(function(x){ return x == "name";});
Which will return you an array with the same number of objects, but each object will just have the name element.
Live example: http://jsfiddle.net/8BGmG/

Categories