How to assigning Object into another object (not merging) - javascript

var student={
student1:{
name:"John",
}
}
var student2={
name:"Doe"
}
Resultamt object should contain both student object with their object's name
Like this :-
students={
student1={name:"John"},
student2={name:"Doe"}
}

You can use object spread to solve this.
e.g
let student = {
student1: {
name: "John",
},
};
let student2 = {
name: "Doe",
};
let students = {
...student,
student2,
};
console.log(students);

Using spread operation you can combine them.
const students = {
...student1,
...student2
};

Related

Merging values from an array of strings into a nested object in javascript

I want to merge values from an array into a static nested object. The array containing the values is something like this,
['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27']
and the object in which the values has to be merged is,
const person = {
details_1: {
name: null,
hobbies: null,
profession: null
},
details_2: {
age: null
}
};
I want my output object to look like below,
const updated_person = {
details_1: {
name: 'ABC XYZ',
hobbies: [M,N,O,P],
profession: 'S'
},
details_2: {
age: 27
}
};
Thanks a lot for your help!
I made another solution with a different approach.
Here I used an interface weher I described the desired data structure.
In the second part the string array is tranformed into key and value pairs. Thereform are filtered the keys of interface and added into an empty object literal.
const data = ["name=ABC XYZ", "hobbies=[M,N,O,P]", "profession=S", "age=27"];
const dataInterface = {
details_1: { name: null, hobbies: null, profession: null },
details_2: { age: null },
};
function orederData(arr) {
const record = arr.map((item) => {
let [key, value] = item.split("=");
if (value[0] === "[" && value[value.length - 1] === "]") {
value = value.slice(1, value.length - 1).split(",");
}
return { key, value };
});
const dataBlock = {};
Object.keys(dataInterface).map((detail) => {
dataBlock[detail] = {};
Object.keys(dataInterface[detail]).forEach((dataKey) => {
dataBlock[detail][dataKey] = record.filter((record) => {
return record.key === dataKey;
})[0].value;
});
});
return dataBlock;
}
const orderedData = orederData(data);
console.log(orderedData);
You can simply achieve this by iterating the input array.
const arr = ['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27'];
const person = {
details_1: {},
details_2: {}
};
arr.forEach(item => {
(item.split('=')[0] !== 'age') ? person.details_1[item.split('=')[0]] = item.split('=')[1] : person.details_2[item.split('=')[0]] = item.split('=')[1]
});
console.log(person);
There is no way to cleanly merge an unstructured array into a structured object such that the array values end up in the appropriately keyed person properties.
javascript does provide the assign() function that merges objects but for YOUR requirements your source data needs to be an object similarly structured and not an array.
so this:
['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27']
would need to become this:
const source= [{details_1: {"name":"ABC XYZ", "hobbies":"[M,N,O,P]", "profession":"S"}, details_2: {"age":"27"}}]
such that a call to Object.assign():
const new_person = Object.assign(person, source[0]);
fills this
const person = {
details_1: {
name: null,
hobbies: null,
profession: null
},
details_2: {
age: null
}
};
properly, though you may need to clone or instantiate and empty person first.
or, if person is an Object you could have a fill() method that knows what to do with the array data.

Pushing keys and value from an inside Obj in the Parent object

Despite the fact that the title seems difficult, let me give you a simple example.
I have an object.
{
name:"Ethan"
pets:{cat:"joline",dog:"Momo",bird"Mimi"}
}
My goal is to push the values of the array to the object.
{
name:"Ethan",
cat:"joline",
dog:"Momo",
bird"Mimi"
}
The question is simple and I believe you can approach it in a clever way, thanks.
Simple way to do this is to combine pets object and other properties using spread operator and then delete the pets from result.
const data = {
name:"Ethan",
pets:{cat:"joline",dog:"Momo",bird:"Mimi"}
}
const res = {...data, ...data.pets};
delete res.pets;
console.log(res);
If you want to do it in a functional way you can use the following approach.
Wrap the original element in a array.
Apply map on it.
Destructure pets from the object and store the rest of the properties in other variable.
Return a new object where you spread the rest object and pets.
const data = {
name:"Ethan",
pets:{cat:"joline",dog:"Momo",bird:"Mimi"}
}
const res = [data].map(({pets, ...rest}) => ({...rest, ...pets}))[0]
console.log(res)
The simplest and cleanest way to obtain desired result with destructuring.
const obj = {
name: "Ethan",
pets: { cat: "joline", dog: "Momo", bird: "Mimi" },
};
const { name, pets } = obj;
const result = { name, ...pets };
console.log(result);
Iterating through the elements and values in the object. And spreading the value into the return object
const data = {
name: "Ethan",
pets: {
cat: "joline",
dog: "Momo",
bird: "Mimi"
}
};
function flatten(data) {
let result = {};
for (const key in data) {
const value = data[key];
if (typeof value != 'object') result[key] = value;
else result = { ...result, ... flatten(value)}
}
return result;
}
console.log(flatten(data));
As others have said, this is straightforward with object destructuring. I think it's cleanest when you use parameter destructuring. So a simple function like this should do it:
const promotePets = ({pets, ...rest}) =>
({...rest, ...pets})
const obj = {name: "Ethan", pets: { cat: "joline", dog: "Momo", bird: "Mimi" }};
console .log (promotePets (obj))

How to add attribute to the root of JSON object consists of array of objects?

How to add attribute to the root of JSON object consists of array of objects?
If my JSON object something like that:
[
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
]
I do the following:
worktimeJSON.Id = $('.Js-WorkTime-id').val();
worktimeJSON.Name = $('.Js-WorkTime-name').val();
worktimeJSON.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
And make sure that the jQuery fetching data from the inputs but this doesn't work.
This will change property of all object in array if you want to change in particular then use index for this for exp->
worktimeJSON[0].Id = $('.Js-WorkTime-id').val();
worktimeJSON[0].Name = $('.Js-WorkTime-name').val();
worktimeJSON[0].NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
var worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON = worktimeJSON.map(function(val){
val.Id = $('.Js-WorkTime-id').val();
val.Name = $('.Js-WorkTime-name').val();
val.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
return val;
});
Push can do the job.
let worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON.push
({
id: "someID",
name: "toto",
WorkTimeRegulationId: 42
});
console.log(worktimeJSON);
I structure my object like this:
let WorkTimeRegulationViewModelJSON = {
Id: $('.Js-WorkTimeRegulation-id').val(),
Name: $('.Js-WorkTimeRegulation-name').val(),
NumberOfAvailableRotations: $('.Js-WorkTimeRegulation-rotations').val(),
AssignedWorkTimes: JSON.parse(worktimeJSON)
};

Copy out a child Object in JavaScript

I'm trying to copy out a child Object into a variable, but it seems that by simply declaring it, only the key get's copied. How do I copy out the entire Object? Here's what I'm trying...
const baseObj = {
players: {
player1: {
name: "hello",
details: "something"
},
player2: ...
}
}
const player1Copy = baseObj.players.player1
// I want to grab out the whole object player1 instead of just the key
use Object.assign
DEMO
const baseObj = {
players: {
player1: {
name: "hello",
details: "something"
}
}
}
let cloned = Object.assign({}, baseObj.players.player1);
console.log(cloned);

can you get var name from object with nested objects with lodash?

https://jsfiddle.net/adamchenwei/Lyg2jy61/7/
RESOLVED VERSION:
https://jsfiddle.net/adamchenwei/Lyg2jy61/10/
For some reason findKey for parent top level got undefined
My objective is to get the result = 'myName' with lodash;
var obj = {
myName: {
Adam: 'Man',
},
herName: {
Eve: 'Woman',
},
};
var result = _.findKey(obj, '0'); //as you can see somehow its undefined!
var result2 = _.findKey(obj.myName, '0');
console.log(result);//objective is to get the result = 'myName' with lodash;
console.log(result2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
It looks like what you're actually trying to do is get the first key of an object. To get the keys of an object, you can use _.keys. Then just retrieve the first one.
var obj = {
myName: {
Adam: 'Man',
},
herName: {
Eve: 'Woman',
},
};
console.log(_.keys(obj)[0]);
// Or if you want to do it exclusively with lodash functions
console.log(_.first(_.keys(obj)));
// or
console.log(_.head(_.keys(obj)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
It's not clear what you're after exactly, but using _.findKey on the object you have posted would work like this:
https://jsfiddle.net/Lyg2jy61/8/
var obj = {
myName: {
Adam: 'Man',
},
herName: {
Eve: 'Woman',
}
};
console.log(_.findKey(obj, function(o) { return !!o.Adam; }));
If you just want the first key: _.keys(obj)[0]

Categories

Resources