How to create an object from an Array of key-value pairs?
At the time of writing (2013) JavaScript objects / dictionaries / associative arrays don't have such a constructor natively.
As you said yourself, you can of course build your own function using for instance a functional approach using the reduce
function as explained in one of the other answers. A classic for or newer forEach loop would also work, of course. But there isn't anything built-in.
Edit: It's 2019 and now we have Object.fromEntries, which will give you what you need.
Create an object with key-value pairs from an array
You can use Object.keys to read the name of the key and use the 3rd parameter of array.reduce to get the index of currently processed item.
const myArray = [{value: "test"}, {value: "abc"}, {value: "xyz"}];
//the desired result is this: result = { "value1": "test", "value2": "abc", "value3": "xyz" };
const result = myArray.reduce((agg, item, index) => {
agg[Object.keys(item)[0] + (index + 1)] = item.value;
return agg;
}, {})
console.log(result);
how to take a key value pair from array of objects and create a new object from that key value pair
Try this:
let arr = [
{name: "abcd", value: "xyz"},
{name: "pqr", value: "uvw"}
]
const result = {}
arr.forEach((element) => {
result[element.name] = element.value
})
console.log(result)
How to create a string of key-value pair object from an array of objects?
You can use reduce;
const extractedData = paramData.reduce((obj, item) => {
obj[item.id] = item.value
return obj
}, {})
Please see detailed description here
I also strongly recommend map
and filter
. With reduce
, they are 3 stars of array
Make object from an array of key-value pairs using Lodash
Using lodash's _.fromPairs
:
var result = _.fromPairs(data);
Convert key value pair to array of objects
There exists a method Object.entries
that turns object into list of keys and values already, mapping it to match your required format should not be difficult.
const data = {good: 'value1', key2: 'value2', key3: 'value3'};
const result = Object.entries(data).map(([key, value]) => ({key, value}))
console.log(result)
Convert array of objects to object of key-value pairs
I would do that with Array.prototype.reduce()
, it is even more concise and certainly faster than Object.fromEntries()
:
const items = [{name:'hello',value:['one','two']},{name:'hi',value:['one','two','three']}],
result = items.reduce((r,{name,value}) => (r[name]=value,r), {})
console.log(result)
.as-console-wrapper{min-height:100%;}
How to turn 2 arrays into an object with key value pairs
I am assuming that:
- Both arrays will always have equal lengths. OR
- Keys' array (Array 1) is bigger and you want all the keys from Array 1 and all excess keys will have value
undefined
. OR - Keys' array (Array 1) is smaller and you want to skip all the extra values present in the values' array (Array 2).
You can try the below code, I have used Array reduce() on array 1 and used the index
parameter to access the corresponding value in array 2. For looping the objects
object I have used Object.keys()
and created a new desired object.
So the complete answer for your problem will be something like below:
const objects = {
Battery: {
batteryDetailsKey: ["serial_no", "type", "part_no"],
batteryDetailsVal: ["HJ3CA19347410218LJ98 151 QC", "Extended Range", "4P94-Q051"],
},
Modules: {
moduleDetailsKey: ["serial_no", "part_no", "Cell Count"],
moduleDetailsVal: ["8367532735006109322258160 50", "LJ98-10C779-A51", "32", "6"],
},
};
function twoArraysToObject(arr1, arr2) {
return arr1.reduce((obj, item, index) => {
obj[item] = arr2[index];
return obj;
}, {});
}
const desiredObject = {};
Object.keys(objects).forEach((key) => {
const keyNamesArr = Object.keys(objects[key]);
desiredObject[key] = twoArraysToObject(objects[key][keyNamesArr[0]], objects[key][keyNamesArr[1]]);
});
console.log(desiredObject);
How to convert an array of key-value tuples into an object
Update June 2020
ECMAScript 2021 brings Object.fromEntries
which does exactly the requirement:
const array = [ [ 'cardType', 'iDEBIT' ],
[ 'txnAmount', '17.64' ],
[ 'txnId', '20181' ],
[ 'txnType', 'Purchase' ],
[ 'txnDate', '2015/08/13 21:50:04' ],
[ 'respCode', '0' ],
[ 'isoCode', '0' ],
[ 'authCode', '' ],
[ 'acquirerInvoice', '0' ],
[ 'message', '' ],
[ 'isComplete', 'true' ],
[ 'isTimeout', 'false' ] ];
const obj = Object.fromEntries(array);
console.log(obj);
Creating object array from key-value pairs
Assuming that the JSON records will always be sorted by Group, here is another approach:
var json = [
{ "Group" : "A", "Key" : "Name", "Value" : "John" },
{ "Group" : "A", "Key" : "Age", "Value" : "30" },
{ "Group" : "A", "Key" : "City", "Value" : "London" },
{ "Group" : "B", "Key" : "Name", "Value" : "Hans" },
{ "Group" : "B", "Key" : "Age", "Value" : "35" },
{ "Group" : "B", "Key" : "City", "Value" : "Berlin" },
{ "Group" : "C", "Key" : "Name", "Value" : "José" },
{ "Group" : "C", "Key" : "Age", "Value" : "25" },
{ "Group" : "C", "Key" : "City", "Value" : "Madrid" }
];
var array = [];
var previousGroup = null;
for(var i=0; i<json.length; i++) {
var group = json[i].Group;
if(previousGroup != group) {
array.push({Group: group});
previousGroup = group;
}
array[array.length-1][json[i].Key] = json[i].Value;
}
Here is a working example.
Related Topics
Preloader Wont Ignore Websocket - Pace Js
How to Reduce JavaScript Object to Only Contain Properties from Interface
How to Get an Ajax Get-Request to Wait for the Page to Be Rendered Before Returning a Response
Console.Log() After Setstate() Doesn't Return the Updated State
How to Enable Touch on Multiple Buttons Simultaneously in React Native
How to Include Js.Erb File in View Folder
Javascript: Undefined !== Undefined
Create an Object from an Array of Keys and an Array of Values
How to Get the Browser Language Using JavaScript
How to Get Selector from Jquery Object
Decryption of Aes Created with Sjcl.Js in Ruby
The Best Way to Synchronize Client-Side JavaScript Clock with Server Date
How to Pass Data from JavaScript to Swift Within a Wkwebview
How to Implement Inheritance in Js Revealing Prototype Pattern
How to Parse JavaScript Using Nokogiri and Ruby
How to Find All Subsets of a Set in JavaScript? (Powerset of Array)