I have the below object
{
lookUp: {
id: "123",
text: {
street_address_test: [
{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
},
},
}
I want to append the below (using JavaScript i.e nodejs to be specific)
street_address_uk: [
{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
so that it becomes
{
lookUp: {
id: "123",
text: {
street_address_test: [
{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
street_address_uk: [
{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
},
},
}
I looked at existing Stack Overflow posts and https://stackoverflow.com/a/8889386/4068218 was close but dynamically I will not know street_address_test or street_address_uk.
I went through other Stack Overflow posts as well but most of the solutions were on arrays but as you see mine is not an array.
Any leads are much appreciated.
CodePudding user response:
Considering the array object received has to be assigned always to property text
of lookUp
object you can do the following,
let objectToAssign = {
street_address_test: [{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
street_address_uk: [{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
]
};
let objectToAssignTo = {
lookUp: {
id: "123",
text: {},
},
}
function assignPropToObject(object, globalObject) {
let prop = Object.keys(object);
for (let i = 0; i < prop.length; i ) {
globalObject['lookUp']['text'][prop[i]] = object[prop[i]];
}
console.log(globalObject)
}
assignPropToObject(objectToAssign, objectToAssignTo)
CodePudding user response:
You can use the object spread operator, object1{...object2}
and overwrite nested properties like so.
In the example below, I have assumed that you will accumulate the individual street_address
arrays into a lookUpData
object.
let initObject = {
lookUp: {
id: "123",
text: {},
},
};
let lookUpData = {
street_address_test: [{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
street_address_uk: [{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
};
let newObject = {
...initObject,
lookUp: {
...initObject.lookUp,
text: lookUpData,
},
};
console.log(initObject);
console.log(newObject);
CodePudding user response:
thank you @thisdotutkarsh and @Alex. Your answers helped me. I think I should have been more specific but I managed to get what I want. Pasted the solution below in case if somebody is looking for something similar
let master = {
lookUp: {
id: "123",
text: {
street_address_uk: [
{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
},
},
}
let child = {
lookUp: {
id: "123",
text: {
street_address_US: [
{
pos: 12,
len: 6,
},
{
pos: 3,
len: 8,
},
{
pos: 3,
len: 15,
},
],
},
},
}
const prop = Object.keys(master.lookUp.text);
const bl = Object.keys(child.lookUp.text);
master.lookUp.text[bl[bl.length-1]] = child.lookUp.text[bl[bl.length-1]] ;
console.log(master.lookUp)