JS: How to insert object into array alphabetically by key? [duplicate] - javascript

This question already has answers here:
How can we custom sort JavaScript object keys?
(3 answers)
Closed 24 days ago.
I have the following Javascript object:
let obj = {
a: 1,
b: 2,
d: 4
}
obj["c"] = 3
When I log this, the keys are in the order a, b, d, c. Is there a way to make it so that c is inserted between b and d?

One method is to create a new object with Object.fromEntries after sorting the entries of the original object.
let obj = {
a: 1,
b: 2,
d: 4
}
obj["c"] = 3;
let newObj = Object.fromEntries(Object.entries(obj).sort());
console.log(newObj);
Alternatively, just sort the keys before looping over them.
let obj = {
a: 1,
b: 2,
d: 4
}
obj["c"] = 3;
for (const key of Object.keys(obj).sort()) {
console.log(key, '=', obj[key]);
}

Related

In Javascript, given key/value pairs, return values from array of keys

const pairs = { a : 1, b : 2, c : 3 }
const keyArray = [a, b, c]
I'm trying to get a function or w/e that returns [1, 2, 3]. can't think of anything please help
In javascript all keys of an object are actually strings, and can be addressed using the same strings.
Your code is creating an array containing the values of the - possibly uninitialized - variables a, b and c, which then produces [undefined, undefined, undefined], or else whatever those variables contain.
You need to make keyArray contain strings instead, and then you can use the map() function to produce the desired result:
const pairs = { "a" : 1, "b" : 2, "c": 3 }
const keyArray = ["a", "b", "c"]
const values = keyArray.map(key => pairs[key]);
console.log(values);
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
const keyArray = ['a', 'b', 'c']
for(const item of keyArray)
{
console.log(pairs[item])
}
You need to make your items inside the array and object as strings
Well since it's Javascript
Object.values() should do it.
const keyArray = Object.values(pairs)
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
for(const [key , value] of Object.entries(pairs))
{
console.log(key) // a , b, c
console.log(value) // 1, 2, 3
}

Adding or appending object with object javascript

i am having 2 objects and the code is
Object 1
var existingValue=self.get('objHubDto').ftd.gridDataDTO.gridDTOMap[name].gridDataMap;
Object 2
var newValue = self.get('childDataList')
I need to merge/add/append this two in newvalue value eventhough it having duplicate key values
Following is a very basic example to merge by keeping both values, however, you can create new object rather mutating existing one.
let obj1 = { a: 1, b: 2, c: 3 };
let obj2 = { a: 9, d: 8, e: 7 };
Object.entries(obj2).forEach(([key, val]) => {
obj1[key] = obj1[key] ? [obj1[key], val] : val;
});
console.log(obj1);

Creating object property from a variable name [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 years ago.
given this example:
var obj = {
'a': 1,
'b': 2
};
will be a:1, b:2 as excected. But what if I have:
var b = 'myProperty';
var obj = {
'a': 1,
b: 2
};
I wanted to have a: 1, myProperty: 2 but I still got a: 1, b: 2! How to fix it?
Variables in object property names are only allowed using the bracket notation:
var b = 'myProperty';
var obj = {
'a': 1
};
obj[b] = 2;
console.log(obj.myProperty); // logs 2
Hope this helps!
var b = 'myProperty';
var obj = {
'a': 1
};
obj[b]=2;
console.log(obj)

How to check if one Object partially contains another? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So i am trying to check if one object contains exactly another/ partial. For example, i want to check if { a: 1, b: 2, c: 2 } contains { a: 1, b: 2 }. But has to be in that order. If a is the first element and lines up, the b element will have to line up exactly afterwards. Plus is their anyway i could check there value? Order does matter.
//Here is my code currently:
function whatIsInAName(collection, source) {
var array = [];
var sourceNames = Object.getOwnPropertyNames(source);
for (var i = 0; i < collection.length; i++) {
var collectionNames = Object.getOwnPropertyNames(collection[i])
JSON.stringify(collectionNames).includes(JSON.stringify(sourceNames)) ? array.push(collection[i]) : null
}
return array
}
whatIsInAName([{ a: 1, b: 2 }, { a: 1 }, { a: 1, b: 2, c: 2 }], { a: 1, b: 2 });
Its a exact check but, only for the names. I wish it also compared the values.
It also isn't partially checking for the object in another. Like comaparing { a: 1, b: 2, c: 2 } to contain { a: 1, b: 2 }
Here was the challenge i was given --> https://www.freecodecamp.org/challenges/wherefore-art-thou
You coukd take the keys of the single object for comparing the values and use every for returning the result for filtering the array of objects.
Array#filter for getting parts of the array,
Object.keys for getting an array with own keys of the object,
Array#every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) for checking all keys and values,
in operator for check if the key exist in the object,
Identity/strict equality operator === for checking type and value of the operands.
function compare(array, object) {
return array.filter(function (o) {
return Object.keys(object).every(function (k) {
return k in o && object[k] === o[k];
});
});
}
console.log(compare([{ a: 1, b: 2 }, { a: 1 }, { a: 1, b: 2, c: 2 }], { a: 1, b: 2 }));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I was trying to guide you to figure out the problem on your own in the comments, but if you're just looking for a solution, here is how you can do this using basic JavaScript constructs (nothing fancy like Array#filter and Array#every).
It may be much longer than some other solutions, but it makes use of the basics of JavaScript:
function whatIsInAName(collection, source) {
var array = [];
var sourceNames = Object.getOwnPropertyNames(source);
// loop over each item in collection
for (var i = 0; i < collection.length; i++) {
var matchedProperties = 0;
// loop over each property in source
for (var j = 0; j < sourceNames.length; j++) {
// check whether the property is in collection[i] and
// whether the value matches
if (collection[i].hasOwnProperty(sourceNames[j]) &&
source[sourceNames[j]] === collection[i][sourceNames[j]]) {
matchedProperties += 1;
}
// add to array if all properties matched
if (matchedProperties === sourceNames.length) {
array.push(collection[i]);
}
}
}
return array
}
var result = whatIsInAName([{ a: 1, b: 2 }, { a: 1 }, { a: 1, b: 2, c: 2 }], { a: 1, b: 2 });
console.log(result);

Explanation for in loop JavaScript

Who can explain how this for in loop works and why it's assign keys of object to array
var o = {
a: 1,
b: 2,
c: 3,
d: 4
};
var a = [],
i = 0;
for (a[i++] in o);
console.log(a);
Using a side effect when enumerating the object, and using an empty statement, each key is stored in the array a; first key in a[0], next in a[1] etc.
It is not necessary however since you could just use Object.keys(o)
var o = {
a: 1,
b: 2,
c: 3,
d: 4
};
var a = [],
i = 0;
for (a[i++] in o); // do nothing loop
console.log(a,Object.keys(o));

Categories