Convert JavaScript Array of 2 Element Arrays into Object Key Value Pairs

Convert JavaScript array of 2 element arrays into object key value pairs

You could indeed use Array.prototype.reduce:

function objectify(array) {
return array.reduce(function(p, c) {
p[c[0]] = c[1];
return p;
}, {});
}

where p is the result of the previous iteration, initially {}, and c is the current element of the array.

It's unlikely to be any faster than array.forEach, but it is IMHO cleaner. I don't believe there's any simpler implementation than this.

NB: a function to do exactly this already exists in the Underscore library: _.object(array)

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);

Convert 2 arrays into key value object javascript

let props=["language", "name", "code"];let data=[["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]];let result=data.map( (innerArray) =>{let obj={};innerArray.forEach( (innerData,index) =>{obj[props[index]]=innerData;});return obj;});console.log(result);

How to Convert an Array into Object of key value pair

Using Array.prototype.map() make an iteration over the array, create an array of Object and finally convert that to an object using Object.assign().

var key = ['lat', 'lng'];var array = [17.3850, 78.4867]

var obj = Object.assign({}, ...key.map((e, i) => ({[e]: array[i]})))console.log(obj)

Converting an array into an object with key/value pairs

You need to loop through your API response and build the objects from the array.

let objectArray = []

for(let i = 0; i < arr.length - 1; i+=2){
objectArray.push({"topic": arr[i], "count": arr[i+1]})
}

I'm sure there's an easier way to do it, but this will get you what you need.

See it in action on jsFiddle: https://jsfiddle.net/L6023fn6/1/

convert an array to an object of key value pairs

If I understand correctly, you may try something like this:

const convert = data => {
const [columnsText, ...items] = data;
const columns = columnsText.split(',');

return items.reduce((acc, text) => {
const { person, ...entries } = Object.fromEntries(text.split(',').map((value, i) => [columns[i], value]));
entries.totalPriceForItems = String(entries.cost * entries.amount);

if(acc[person]) {
acc[person].push(entries);
} else {
acc[person] = [entries];
}

return acc;
}, {});
};

const result = convert([
'person,item,cost,amount',
'John,shoes,200,2',
'Bob,glasses,50,3',
'John,shirts,100,5',
]);

console.log(result);

How to convert an array of objects to object with key value pairs

You could use Object.assign and a spread syntax ... for creating a single object with the given array with objects.

var array = [{ name1: "value1" }, { name2: "value2" }],    object = Object.assign({}, ...array);    console.log(object);

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);

convert 2 arrays into key value object, one array hold the keys, they second is nested array of matching indexed values

I think the OP is asking how to "zip" two arrays, where one has keys and one has values. If so, Object.fromEntries() is very useful.

A simple zip, goes like this:

// a simple zip
function zip(keys, values) {
return Object.fromEntries(
keys.map((key, index) => [key, values[index]])
);
}

The OP appears to want the lead element in the values array to be a specially named field in the new object as well as the key of the resulting object. Here, applying the simple zip...

function zip(keys, values) {
return Object.fromEntries(
keys.map((key, index) => [key, values[index]])
);
}

// the value array contains an "id" element at the start
// produce an object that looks like { id: number, values: {...} }
function objectFromValues(keys, values) {
return { id: values[0], values: zip(keys, values.slice(1)) }
}

const valuesArr = [
[1, "A", "B", "C"],
[2, "D", "E", "F"]
];

const keys = ["keyA", "keyB", "keyC"];

const result = valuesArr.reduce((acc, values) => {
acc[values[0]] = objectFromValues(keys, values);
return acc;
}, {});

console.log(result)


Related Topics



Leave a reply



Submit