how to convert this answer to an Object? [duplicate] - javascript

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 28 days ago.
This post was edited and submitted for review 28 days ago.
I am trying to convert my answer in an object because it is showing an array in the console?
This is my object
const myObject = {0: 54,1: 77,2: 79,3: 39,4: 37,5: 15,6: 23,7: 2,8: 4,9: 8,s: 439,k: 84,i: 654,p: 441,t: 954,o: 799,m: 236,a: 936,n: 675,c: 556,e: 1211,l: 597,g: 117,u: 596,r: 973,h: 200,f: 239,d: 284,b: 176,y: 281,w: 88,v: 174,j: 53,x: 79,'[': 65,']': 65,q: 11,_: 32,z: 3,};
Here I sort the object according to values:
const myObject = {0: 54,1: 77,2: 79,3: 39,4: 37,5: 15,6: 23,7: 2,8: 4,9: 8,s: 439,k: 84,i: 654,p: 441,t: 954,o: 799,m: 236,a: 936,n: 675,c: 556,e: 1211,l: 597,g: 117,u: 596,r: 973,h: 200,f: 239,d: 284,b: 176,y: 281,w: 88,v: 174,j: 53,x: 79,'[': 65,']': 65,q: 11,_: 32,z: 3,};
const finalAns = Object.entries(myObject).sort(function (a, b) {
return b[1] - a[1];
});
console.log(finalAns);
This is my output of consol.log.
I am getting finalAns as an Array, but I want to print answer as an object and the object should be sorted according to its values?

My understanding is that you are getting the correct answer, but you want to convert it to an object? If so, you could:
var finalAnsObject = JSON.stringify(finalAns)
Updated way (getting a javascript object, not a JSON string):
const newObject = Object.assign({}, ...finalAns.map(element => ({ [element[0]]: element[1] })));

Related

JavaScript: Is there a better way to construct an object from query strings of a url [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have a url string like this "http://url.com/foo/aa=342&bb=66"
and I need to construct an object from it
{ aa: '342', bb: '66' }
Here is my attempt
function constructFromUrl(url) {
return url.split('/').at(-1).split('&').reduce((accu, curr) => {
const [key, value] = curr.split('=')
accu[key] = value
return accu
},{})
}
It works ok but I feel like it is really brittle. Is there any better way of handling this?
Also, I am really bad at naming things - is there a better name for such a function?
const getQueryParams = (urlStr) => Object.fromEntries([
...new URL(urlStr).searchParams
])
Note however that this will fail for your example URL string, because it's malformed — the query string must be separated with a ?, like this:
http://url.com/foo/?aa=342&bb=66
You can parse the parameters with the URLSearchParams constructor, then use Object.fromEntries:
const url = "http://url.com/foo/aa=342&bb=66"
const params = url.split("/").slice(-1)[0]
const result = Object.fromEntries(new URLSearchParams(params))
console.log('params:', params)
console.log(result)

How to compare two different Object keys and update it's value if keys are same in Javascript? [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 2 years ago.
Here i am having two different objects :
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
result should be comparing this above two objects and check if the key are same , then update the oldObject value with newObject . The result has to be like this
let updatedObject = {name:"Dhanush kumar S",age:23,sex:"Male",education:"Btech"}
I tried by doing something like this, but this doesnt help. Your help is much appreciated.
const compareObjects = () => {
for (let [key,value] in oldObject) {
if (newObject.hasOwnProperty(key)) {
oldObject[newObject[key]] = newObject[value]
delete oldObject[key]; //remove old entry
}
}
console.log(oldObject)
}
compareObjects()
You can do this by using the spread syntax.
Just spread the old object first followed by the new object.
Matching keys if any would be updated by the values from the new object and new keys in the new object would be added:
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
const merge = (oldObj, newObj) => {
return {...oldObj, ...newObj};
}
console.log(merge(oldObject, newObject));

How to Do full copy from Slice? [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 4 years ago.
I an array like this
#observable data = [{a: 1}, {b: 1}, {c:1}];
#observable sampleData = [];
I want to do a slice
this.sampleData = this.data .slice(0, 1);
this.sampleData[0].a = 2;
I want "2" to effect the the record in "sampleData" not in the "data" array what is happening now.
So you basically want to create a copy of every sliced element. You can do it like this:
this.sampleData = this.data.slice(0, 1).map(obj => ({ ...obj }))
Or using Object.assign:
this.sampleData = this.data.slice(0, 1).map(obj => Object.assign({}, obj))
Be advised that this is only a shallow copy, so if your object has nested structure, you would have to perform a deep copy instead.

Javascript array of objects check for key [duplicate]

This question already has answers here:
How do I find an array item with TypeScript? (a modern, easier way)
(5 answers)
Closed 5 years ago.
So my question how can I check this array of objects by "key" for eg I want to check if the key 3892 is there, I have tried with indexOf but no luck, I can't use a loop.
You can use some() and hasOwnProperty()
var array = [{3892: 'value'}, {1234: 'value'}];
var check = array.some(obj => obj.hasOwnProperty(3892));
console.log(check)
You can chain Object.keys with Array.prototype.includes to achieve that
Object.keys(myObject).includes(myKey);
const myObject = { name: 'Peter' };
const myKey = 'name';
const result = Object.keys(myObject).includes(myKey);
console.log(`Includes key ${myKey}? `, result);

How can I get fields from one object and add them to another in Javascript? [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 9 years ago.
I have the following:
$scope.book1 = {
a = 1,
b = 2
}
I'm getting this from my database:
$scope.book2 = {
title = 2,
author = 'joe'
}
How can I update the book1 object with the data from book2 so that it has all four fields?
Note that my users are using IE9 and above. If it's possible I would like to use lodash but I'm not sure that's possible as I want the result to go into the book1 object and not to create a new object.
If you need to create your extend function
Object.prototype.extend = function(x) {
for(i in x)
this[i] = x[i];
};
$scope.book1.extend($scope.book2);
If you are using angularjs you can have a look at http://docs.angularjs.org/api/angular.extend
angular.extend($scope.book1, $scope.book2);

Categories