Create object from array
Simply
const obj = {};
for (const key of yourArray) {
obj[key] = whatever;
}
or if you prefer "functional" style:
const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {});
using the modern object spread operator:
const obj = yourArray.reduce((o, key) => ({ ...o, [key]: whatever}), {})
Example:
console.log(
[
{ id: 10, color: "red" },
{ id: 20, color: "blue" },
{ id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})
);
Convert Array to Object
ECMAScript 6 introduces the easily polyfillable Object.assign
:
The
Object.assign()
method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
For custom keys you can use reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
Use typescript to create object from array of objects
Sure there is. This solution does not need as const
like @Vija02's (although it is perfectly fine if it does).
Map over all possible keys in the array, then get only the type of that key using Extract
:
type CreateFrom<T extends ReadonlyArray<unknown>> = { [K in keyof T[number]]-?: Extract<T[number], { [_ in K]: any }>[K] };
Then you'd just use this type in a supposed function:
function createFrom<T extends ReadonlyArray<unknown>>(list: T): CreateFrom<T> {
// ... for you to implement!
}
Note that you might need to cast the return type. I don't think TypeScript will be too happy with this one.
And to finish it off, this is a playground demonstrating the solution.
How to create Object with nested Objects from an Array
You can use reduceRight
like so:
let obj = arr.reduceRight((rest, value) => ({ value, rest }), null);
It starts building the object from the inside out; it starts by creating the innermost object and then it uses that object as the rest
property for the next outer object and so on until there are no more items in the array.
Demo:
let obj = [1, 2, 3, 4].reduceRight((rest, value) => ({ value, rest }), null);
console.log(obj);
How do I create an object from array of objects using javascript?
You could use reduce
to iterate through all the array items and build a new object with the desired format:
const arr = [{name:"abc", age:10},{name:"xyz", age:20},{name:"asd", age:12}];
const result = arr.reduce((acc, currentValue) => {
// grab the name in a separate variable and keep the rest of the object in another using object destructuring
const { name, ...rest } = currentValue;
// use the name as a key in the result and assign the rest as the value
acc[name] = rest;
return acc;
}, {});
console.log(result)
Create an object from an array of keys and an array of values
var keys = ['foo', 'bar', 'baz'];var values = [11, 22, 33]
var result = {};keys.forEach((key, i) => result[key] = values[i]);console.log(result);
Create an object from an array of objects with custom key values
To get the property name, extract the title
and replace its space-characters with the upper-case character. Then, it's as simple as reduce
-ing into an object:
const input=[{amount:23,bill:47,otherData:null,title:'cool title'},{amount:223,bill:427,otherData:null,title:'cooler title'},{amount:2313,bill:437,otherData:null,title:'super cool title'},{amount:123,bill:147,otherData:null,title:'coolest title'}]
console.log( input.reduce((a, item) => { const { title } = item; const camel = title.replace(/ ./g, chars => chars[1].toUpperCase()); a[camel] = item; return a; }, {}));
Create new Array of object based on the Property Value
There should be a looping logic
Logic
- Loop through the
data
array. Which is the input. - Loop through
cloudServices
nodes in each node of thedata
and find the distict value. - Loop through this distinct values and and generate a group of each distict value using
Array.filter
. - Aggregate all the remainig values from each node in data array except the
cloudServices
node. - Generate a final object with this remaining values and the above generated group.
ES5 implementation
var data = [{ "id": 14042, "created": "2020-03-18T10:11:40.000Z", "enterpriseId": 437, "siteId": 6302, "activationKey": "PMZP-NGRU-HE64-SA5M", "activationKeyExpires": "2021-08-04T16:21:33.000Z", "activationState": "ACTIVATED", "activationTime": "2020-03-18T17:05:27.000Z", "softwareVersion": "4.3.0", "buildNumber": "R430-20210720-GA-64951-67694-6911a00421", "factorySoftwareVersion": "3.3.0", "factoryBuildNumber": "R330-MTHD-20190328-GA", "softwareUpdated": "2021-09-24T11:21:49.000Z", "selfMacAddress": "50:9a:4c:e4:1e:c0", "deviceId": "93AB7D33-87B7-42AA-BC0B-7D8255E069AD", "logicalId": "d25a6121-bf16-4512-b490-2dc5c45e11b8", "serialNumber": "F0TFXC2", "modelNumber": "edge610", "deviceFamily": "EDGE6X0", "name": "SDALM-BAYNARD-LAB-4", "dnsName": null, "description": "Dual Internet Site in Baynard", "alertsEnabled": 1, "operatorAlertsEnabled": 1, "edgeState": "CONNECTED", "edgeStateTime": "2021-09-24T11:23:00.000Z", "isLive": 0, "systemUpSince": "2021-09-24T11:20:55.000Z", "serviceUpSince": "2021-09-24T11:31:06.000Z", "lastContact": "2021-10-04T14:06:47.000Z", "serviceState": "IN_SERVICE", "endpointPkiMode": "CERTIFICATE_REQUIRED", "haState": "UNCONFIGURED", "haPreviousState": "UNCONFIGURED", "haLastContact": "0000-00-00 00:00:00", "haSerialNumber": null, "bastionState": "UNCONFIGURED", "modified": "2021-10-04T14:06:47.000Z", "customInfo": "", "isHub": false, "cloudServices": [{ "state": "UP", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000005-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.2.1", "local_public_ip": "217.38.39.43", "nvs_ip": "165.225.16.236", "pathId": "211262ED9DE488A22CFEBBA9809092B32B937912", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 11, "avg": 7, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE5" }, { "state": "STANDBY", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000005-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.2.1", "local_public_ip": "217.38.39.43", "nvs_ip": "165.225.196.39", "pathId": "26434D16946CFD147D5DDFA50647F48A0066AB31", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 10, "avg": 6, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE5" }, { "state": "STANDBY", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000006-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.1.1", "local_public_ip": "217.38.39.41", "nvs_ip": "165.225.196.39", "pathId": "9B88047C891952D8A661F30A8E7C0A5842AB8544", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 16, "avg": 6, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE6" }, { "state": "UP", "timestamp": "2021-10-04T14:01:50.638Z", "link": "00000006-bf16-4512-b490-2dc5c45e11b8", "local_interface_ip": "172.16.1.1", "local_public_ip": "217.38.39.41", "nvs_ip": "165.225.16.236", "pathId": "DB965CA91A564DE09027F8D766F92CD0DDB54405", "segmentId": 0, "segmentLogicalId": "cd948075-e95f-4c7c-beb2-0fcde7e17c62", "l7_check": "UP", "l7_check_rtt": { "max": 1063, "avg": 41, "min": 5 }, "site": { "id": 60282, "logicalId": "717f67c5-7426-4689-a74c-b58c93d4c3b1", "data": { "customSourceIp": "", "linkInternalLogicalId": "00000005-bf16-4512-b490-2dc5c45e11b8", "primaryAddressing": { "internalRouterIp": "172.22.60.145", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.146", "internalZenMask": "255.255.255.255" }, "secondaryAddressing": { "internalRouterIp": "172.22.60.149", "internalRouterMask": "255.255.255.255", "internalZenIp": "172.22.60.150", "internalZenMask": "255.255.255.255" }, "useCustomSourceIp": false } }, "provider": { "name": "L7HC-LON3-MAN1-GRE", "id": 549697, "logicalId": "d5a058dc-6202-494c-b65d-6a8c273ed1c4", "data": { "primaryServer": "165.225.16.236", "secondaryServer": "165.225.196.39", "automateDeployment": false, "enableTunnels": true, "sharedIkeAuth": false, "maxTunnelsPerIkeIdentity": 128, "l7HealthCheck": { "enabled": true, "probeIntervalSec": 5, "numOfRetries": 3, "rttThresholdMs": 3000, "cloud": "zscloud.net" }, "provider": "zscalerWebSecurityService" } }, "segmentName": "Global Segment", "interface": "GE6" }] }];
//Function to find distinct valies of an object array with specific key
function distinct(dataArray, key) {
var distinctList = [];
dataArray.forEach(function (node) {
if (distinctList.indexOf(node[key]) === -1) {
distinctList.push(node[key]);
}
});
return distinctList;
}
// Reference https://stackoverflow.com/a/34710102/6099327
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) {
continue;
}
if (!Object.prototype.hasOwnProperty.call(obj, i)) {
continue;
}
target[i] = obj[i];
}
return target;
}
var parsedOutput = [];
data.forEach(function (dataNode) {
var distinctInterfaces = distinct(dataNode.cloudServices, "interface");
var remainingProperties = _objectWithoutProperties(dataNode, ["cloudServices"]);
var output = remainingProperties;
distinctInterfaces.forEach(function (interface) {
output[interface] = dataNode.cloudServices.filter(function (node) {
return node.interface === interface;
});
});
parsedOutput.push(output);
});
console.log(parsedOutput);
Type-safe generic reduce util to create object from array
The biggest problem is that records
is being inferred as type:
{
name: string;
id: number;
data: string[];
}[]
Which means keyBy(records, 'name')
can only give you back string
. If you add a as const
assertion to records
, then you can get some literal strings and you have stronger types to work with.
const records = [
{ name: "foo", id: 1, data: ["foo"] },
{ name: "bar", id: 2, data: ["bar"] },
{ name: "baz", id: 3, data: ["baz"] }
] as const;
Then you need to type your reduce
'd result object as
Record<T[K] & ObjectKey, T>
or
Record<T[K] & ObjectKey, T[K2]>
so that the keys from the generic T
are used.
The T[K] & ObjectKey
with an invalid key type will resolve to never
, but you will also throw a runtime exception there so that doesn't matter much.
And lastly, you can can use overloading to declare multiple signatures to make this one function. This will have two signatures:
// One key
function keyBy<
T extends object,
K extends keyof T
>(
collection: readonly T[],
key: K
): Record<T[K] & ObjectKey, T>
// Two keys
function keyBy<
T extends object,
K extends keyof T,
K2 extends keyof T
>(
collection: readonly T[],
k: K,
k2: K2,
): Record<T[K] & ObjectKey, T[K2]>
And an implementation with something like:
// Implementation
function keyBy<
T extends object,
K extends keyof T,
K2 extends keyof T
>(
collection: readonly T[],
k: K,
k2?: K2,
): Record<T[K] & ObjectKey, T[K2]> | Record<T[K] & ObjectKey, T> {
return collection.reduce((acc, curr) => {
const valueAtKey = curr[k];
if (isValidKey(valueAtKey)) {
if (k2) return { ...acc, [valueAtKey]: curr[k2] };
return { ...acc, [valueAtKey]: curr };
}
throw new Error("T[K] is not a valid object key type");
}, {} as Record<T[K] & ObjectKey, T[K2]> | Record<T[K] & ObjectKey, T>);
}
And now this works:
const testA = keyBy(records, "name");
testA.foo.data // readonly ["foo"] | readonly ["bar"] | readonly ["baz"]
const testB = keyBy(records, "name", "data");
testB.foo // readonly ["foo"] | readonly ["bar"] | readonly ["baz"]
Playground
Dynamically creating an object with an array inside
To add the object to an array you should use the array method .push()
.
You could do it in the following way:
// Object which has a property `items`, where we will store product objects
var main = {
items: []
};
// Create the full product object
var product = {
name: "T-Shirt";
quantity: "1";
category: "PHYSICAL_GOODS";
unit_amount: {
currency_code = "USD";
value = "90.00";
}
};
// Push the new object to the `items` array
main.items.push(product);
Related Topics
JavaScript Es6 Cross-Browser Detection
Event Listener for When Element Becomes Visible
Getting Image Dimensions Using JavaScript File API
Get Character Value from Keycode in JavaScript... Then Trim
Typescript Compile to Single File
Jquery Clone Form Fields and Increment Id
Detect When a Window Is Resized Using JavaScript
Browserify, Babel 6, Gulp - Unexpected Token on Spread Operator
Copy to Clipboard in Chrome Extension
Find Day Difference Between Two Dates (Excluding Weekend Days)
How to Listen for a Click-And-Hold in Jquery
Switch Statement for String Matching in JavaScript
Differencebetween Using Constructor VS State = {} to Declare State in React Component
Javascript/Jquery: Set Values (Selection) in a Multiple Select