Combine two json sections into one json object [duplicate] - javascript

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 5 years ago.
I would like to combine topData and bottomData into completeData.
var topData = {
"auth": "1vmPoG22V3qqf43mPeMc",
"property" : "ATL-D406",
"status" : 1,
"user" : "test001#aaa.com",
"name" : "Abraham Denson"
}
var bottomData = {
"agent" : "pusher#agent.com",
"agency" : "Thai Tims Agency",
"agentCommission" : 1000,
"arrival" : "arrive 12pm at condo",
"departure" : "leaving room at 6pm",
}
var completeData = topData.concat(bottomData)
Since these are not arrays, concat wont work here.
Can this be done without making foreach loops?

You can use Object.assign() to concatenate your objects.
var newObj = Object.assign({}, topData, bottomData)
From MDN:
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.
var topData = {
"auth": "1vmPoG22V3qqf43mPeMc",
"property" : "ATL-D406",
"status" : 1,
"user" : "test001#aaa.com",
"name" : "Abraham Denson"
}
var bottomData = {
"agent" : "pusher#agent.com",
"agency" : "Thai Tims Agency",
"agentCommission" : 1000,
"arrival" : "arrive 12pm at condo",
"departure" : "leaving room at 6pm",
}
var completeData = Object.assign({}, topData, bottomData);
console.log(completeData);

You can use Object.assign.
var topData = {
"auth": "1vmPoG22V3qqf43mPeMc",
"property": "ATL-D406",
"status": 1,
"user": "test001#aaa.com",
"name": "Abraham Denson"
}
var bottomData = {
"agent": "pusher#agent.com",
"agency": "Thai Tims Agency",
"agentCommission": 1000,
"arrival": "arrive 12pm at condo",
"departure": "leaving room at 6pm",
}
var completeData = Object.assign(topData, bottomData);
console.log(completeData)
It return the target object which mean properties from bottomData will be added to topData

var completeData = {...topData, ...bottomData};
This is object spread syntax.

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.

Convert string to date based on key [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
I'm writing a js code that takes in a JSON of string arrays, that also has dates formatted as strings in it. Below is a sample code of the same.
var prods = [
{
"id": "56e535de-319f-4612-be83-3084a060b77e",
"createdDate": "2021-04-28T11:34:54.975",
"modifiedDate": "2021-04-28T11:34:54.976"
},
{
"id": "55753a5d-377d-4038-baf0-5ecbf620601a",
"createdDate": "2021-04-27T16:22:02.621",
"modifiedDate": "2021-04-27T16:22:02.621"
},
{
"id": "e9593d91-d884-40e8-8239-5f69794f2b3a",
"createdDate": "2021-04-27T15:29:55.737",
"modifiedDate": "2021-04-27T15:29:55.737"
}
];
prods = prods.map(function(a) {
a.createdDate = Date.parse(a.createdDate);
return a;
});
console.log(prods)
Here I'm able to convert for createdDate. I want to know how I can do for both createdDate as well as modifiedDate by looping over the JSON.
Thanks
something like that ?
const prods =
[ { id : '56e535de-319f-4612-be83-3084a060b77e'
, createdDate : '2021-04-28T11:34:54.975'
, modifiedDate : '2021-04-28T11:34:54.976'
}
, { id : '55753a5d-377d-4038-baf0-5ecbf620601a'
, createdDate : '2021-04-27T16:22:02.621'
, modifiedDate : '2021-04-27T16:22:02.621'
}
, { id : 'e9593d91-d884-40e8-8239-5f69794f2b3a'
, createdDate : '2021-04-27T15:29:55.737'
, modifiedDate : '2021-04-27T15:29:55.737'
}
]
prods.forEach((el,i,arr)=>
{
arr[i].createdDate = Date.parse(el.createdDate)
arr[i].modifiedDate = Date.parse(el.modifiedDate)
})
console.log(prods)
.as-console-wrapper {max-height: 100%!important;top:0;}

How to split and get as a key value pair object in an array in Javascript [duplicate]

This question already has answers here:
javascript: convert two dimensional array to array of objects using the first 'row' to define properties
(8 answers)
Closed 2 years ago.
First I'm a newbie to JS... now I have an array with some weird data like below;
var data = [
[21062,5000,0.1,0.2,0.3,0.4,0.5],
[21063,6000,0.11,0.21,0.32,0.45,0.51]
]
I need to create a key name for every comma separator with it's value and present it as a object inside an array
Expected output :
data: [
{"productId" : "21062",
"amount" : "5000",
"tax1" : "0.1",
"tax2" : "0.2",
"tax3" : "0.3",
"tax4" : "0.4",
"tax1" : "0.5"
},
{"productId" : "21063",
"amount" : "6000",
"tax1" : "0.11",
"tax2" : "0.21",
"tax3" : "0.32",
"tax4" : "0.45",
"tax1" : "0.51"
}
]
You could achieve it with a combination of .map and .forEach
var data = [
[21062, 5000, 0.1, 0.2, 0.3, 0.4, 0.5],
[21063, 6000, 0.11, 0.21, 0.32, 0.45, 0.51]
]
let obj = data.map(arr=>{
let o = {
productId:arr[0],
amount:arr[1]
}
arr.forEach((e,i)=>{
if (i > 1){
o[`tax${i-1}`] = e;
}
})
return o;
})
console.log(obj);

Extract fields from Json based on a list in Javascript [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 3 years ago.
I'm trying to extract some of the fields from a Json response and push them into a Javascript array. I want the selection of the fields to be configurable. Here is what I'm doing:
Consider this as my JSON string:
{
"id" : "1234",
"orderNumber" : "1196",
"createdOn" : "2019-07-02T12:03:39.697Z",
"modifiedOn" : "2019-07-02T12:25:52.126Z",
"testmode" : false,
"customerEmail" : "a#b.com",
"billingAddress" : {
"firstName" : "John",
"lastName" : "Doe",
"address1" : "Wall Street",
"address2" : null,
"city" : "NYC",
"state" : "NY",
"countryCode" : "US",
"postalCode" : "12345",
"phone" : "1122334455"
}
}
Say I want to extract some of the fields (defined in the FIELDS variable) and push them in an array.
# NOTE: the variable `data` here is my json object
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']
var lineItem = []
# parse the data (my Json object)
for (var i = 0; i < FIELDS.length; i++){
lineItem.push(data[FIELDS[i]])
}
So, this seems to be working OK for the first level (the id, orderNumber and customerEmail) but not for the billingAddress.firstname, etc. This is what I'm wondering about.
My intent is to be able to modify the definition in the FIELDS variable without needing to make any change to the logic in the code.
Hope this makes sense.
Thanks!
As long as there are no periods in the key names this will work.
var data = {
"id" : "1234",
"orderNumber" : "1196",
"createdOn" : "2019-07-02T12:03:39.697Z",
"modifiedOn" : "2019-07-02T12:25:52.126Z",
"testmode" : false,
"customerEmail" : "a#b.com",
"billingAddress" : {
"firstName" : "John",
"lastName" : "Doe",
"address1" : "Wall Street",
"address2" : null,
"city" : "NYC",
"state" : "NY",
"countryCode" : "US",
"postalCode" : "12345",
"phone" : "1122334455"
}
};
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName'];
var lineItem = [];
for (var i = 0; i < FIELDS.length; i++){
let obj = data;
let parts = FIELDS[i].split(".");
while(parts.length) obj = obj[parts.shift()];
lineItem.push(obj)
}
console.log(lineItem);
You just need a function that will split that path on . and traverse the JSON data. With that you can just map() over your fields.
let data = {"id" : "1234","orderNumber" : "1196","createdOn" : "2019-07-02T12:03:39.697Z","modifiedOn" : "2019-07-02T12:25:52.126Z","testmode" : false,"customerEmail" : "a#b.com","billingAddress" : {"firstName" : "John","lastName" : "Doe","address1" : "Wall Street","address2" : null,"city" : "NYC","state" : "NY","countryCode" : "US","postalCode" : "12345","phone" : "1122334455"}}
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']
// split an traverse
const getFromPath = (path, data) => path.split('.')
.reduce((curr, p) => curr && curr[p], data) // check for curr incase path is undefined
console.log(FIELDS.map(p => getFromPath(p, data)))
The function getFromPath will return undefined if any part of the traversal is not found in the object.

How to address dynamic object keys [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
How to access object using dynamic key? [duplicate]
(3 answers)
Closed 8 years ago.
I need to access object properties with dynamic keys which has persistent structure but different keys, like on one occasion it could be:
var ty_tabs=[{
"key1" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}],
"key2" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}]
}]
and on another one:
var ty_tabs=[{
"key3" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}],
"key4" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}]
}]
How do I adopt my code:
var b,a,d1,d2,d3;
for (b = 0 , a = ty_tabs.length; b < a ; ++b){
d1 = ty_tabs[b].key1[0].d1;
d2 = ty_tabs[b].key1[0].d2;
d3 = ty_tabs[b].key1[0].d3;
}
To access properties with varying keys:
d1 = ty_tabs[b].?[0].d1;
d2 = ty_tabs[b].?[0].d2;
d3 = ty_tabs[b].?[0].d3;
If you don't know about the keys of an object, but need all keys present within an it, you can use Object.keys():
var b,a,d1,d2,d3, i, keys;
for (b = 0 , a = ty_tabs.length; b < a ; ++b){
keys = Object.keys( ty_tabs[b] );
for( i=0; i<keys.length; i++ ) {
d1 = ty_tabs[b][ keys[i] ][0].d1;
d2 = ty_tabs[b][ keys[i] ][0].d2;
d3 = ty_tabs[b][ keys[i] ][0].d3;
}
}
Object.keys() is rather well supported. For older versions of IE, you can use the polyfill provided at MDN

Categories