How to access js objects where keys aren't known - javascript

How to access object elements in the example below where the keys are unknown
var person={{name:"john",username:"clap"},{name:"sandr",username:"poss"}}
Any help would be appreciated

This might help you. You can use a for...in loop to loop over the keys or values of an object.
var obj = {a: 1, b: 2, c: 3};
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

Related

Update an object with matching properties and ignore new properties

I'm using Typescript and I would like to update an object with another, only on the matching keys.
// Destination
objectOne = {
a: 0,
b: 0,
};
// Source
objectTwo = {
a: 1,
b: 1,
c: 1,
};
// Expected
result = {
a: 1,
b: 1,
};
// Current solution
const current = {};
Object.keys(objectTwo).forEach(key => key in objectOne ? current[key] = objectTwo[key] : null);
console.log(current);
is there a one-liner (i.e. not a custom function that iterates over the keys) that would ignore the property c in the source ? I would also like to avoid using libraries such as lodash or JQuery.
Duplicate EDIT my question isn't about merging two objects, my question is about ignoring the fields in the second object, that aren't in the first object.
After a while without answers, it seems the shortest solution is the one I provided myself :
Object.keys(newObj).forEach(key => key in oldObj? result[key] = newObj[key] : null)
const result = Object.keys(objectOne)
.reduce((init, key) => Object.assign(init, {[key]: objectTwo[key]}) , {});
I think there is no built-in function to accomplish what you need, rather than a custom one with iterating over keys of the first object and values of the second one:
const objectOne = {
a: 0,
b: 0
};
const objectTwo = {
a: 1,
b: 1,
c: 1,
};
const result = Object.keys(objectOne).reduce((all, key) => {
all[key] = objectTwo[key] || objectOne[key];
return all;
},{});
console.log(result);

Combining two objects but if first object already has a property ignore the property in second object [duplicate]

This question already has answers here:
How to add properties from this object to another object?
(3 answers)
Closed 6 years ago.
Given two objects, "extend" adds properties from the 2nd object to the 1st object.
Notes:
Add any keys that are not in the 1st object.
If the 1st object already has a given key, ignore it (do not overwrite the property value).
Do not modify the 2nd object at all.
var obj1 = {
a: 1,
b: 2
};
var obj2 = {
b: 4,
c: 3
};
extend(obj1, obj2);
console.log(obj1); // --> {a: 1, b: 2, c: 3}
I was able to get this far :
function extend(obj1, obj2) {
for (var key in obj2) {
obj1[key] = obj2[key];
}
return obj1;
}
which logged:
{a: 1, b: 4, c: 3}
I've been cracking my skull trying to figure this out for the passed two days or so. Tried googling and everything. Thanks in advance :)
Basically, you just need to iterate through each key on the 2nd object and see if the first object has that key or not.
The iteration can be done using a for..in loop, as you know. The part your're missing is how to check if an object already has a given property. That's what hasOwnProperty is for.
function extend(obj1, obj2) {
// Iterate over every (enumerable) key in obj2
for (var key in obj2) {
// If obj1 does not have a key by this name,
// add it to obj1
if (!obj1.hasOwnProperty(key)) {
obj1[key] = obj2[key];
}
}
}
var obj1 = {
a: 1,
b: 2
};
var obj2 = {
b: 4,
c: 3
};
extend(obj1, obj2);
console.log(obj1); // --> {a: 1, b: 2, c: 3}

Flatten an array of objects containing key\values

Say I have the follow array of objects storing a single key\value pair:
var someArray = [
{foo: 1},
{bar: 2}
];
I would like to flatten this array into a single object, where each key from the original objects become a property of the new single object like so:
someObject = {
foo: 1,
bar: 2
}
I will always have unique keys, and only ever one key\value pairing.
I know if I loop over the array in a foreach, then I can only access the index and value of the item, e.g.
0: {foo: 1}
I want to be able to loop over, and when accessing the item read the key and value separately so I can append onto my new object.
I feel like lodash should be able to help here, but I'm struggling to find whic of their methods could help.
Can someone point me in the right direction?
Thanks
No need for lodash here you can just use Object.assign() and spread syntax.
var someArray = [
{foo: 1},
{bar: 2}
];
var obj = Object.assign({}, ...someArray)
console.log(obj)
You can also use apply instead of spread syntax
var obj = Object.assign.apply({}, someArray)
var someArray = [
{foo: 1},
{bar: 2}
];
var obj = Object.assign.apply({}, someArray)
console.log(obj)
You could iterate and use Object.assign to get a new object with all properties.
var someArray = [{ foo: 1 }, { bar: 2 }],
result = someArray.reduce(function (r, a) {
return Object.assign(r, a);
}, {});
console.log(result);
This can be done quickly using reduce and Object assign:
var someArray = [
{foo: 1},
{bar: 2}
];
var result = someArray.reduce((acc, obj) => Object.assign(acc, obj), {})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to compare two JSON values based on the key name in javascript?

I have two JSON arrays like
array1=[{a:1,b:2,c:3,d:4}]
&
array2=[{a:2,b:5,c:3,d:4}]
Is there any method to find the value of one of the keys in array1 present in array 2.Here in the array 1 key b contains the value 2,and array2 also contain a key a with value 2. How can I capture the key name of array 2 which has the same value for one of the keys in array.
I don't quite understand if you are interested in operating on arrays or objects - as your example is a pair of single element arrays, and the comparison is clearly between the objects in the arrays.
That said, if your goal is to compare two objects, and return the set of keys that are the same for both, you would do something like
obj1 = {a:1,b:2,c:3,d:4};
obj2 = {a:2,b:5,c:3,d:4};
function sameKeys(a,b) {
return Object.keys(a).filter(function(key) {
return a[key] === b[key];
});
}
console.log(sameKeys(obj1, obj2));
When I run this, I get:
[ 'c', 'd' ]
I hope that is what you were asking...
Wrote a prototype function to compare an object against another.
var obj1 = {a: 1, b: 2, c: 3, d: 4};
var obj2 = {a: 2, b: 4, c: 100, d: 200}
Object.prototype.propertiesOf = function(visitorObj) {
result = {};
//Go through the host object
for (thisKey in this) {
//Exclude this function
if (!this.hasOwnProperty(thisKey))
continue;
//Compare the visitor object against the current property
for (visitorKey in visitorObj) {
if (visitorObj[visitorKey] === this[thisKey])
result[visitorKey] = thisKey;
}
}
return result;
}
console.log(obj1.propertiesOf(obj2));
Simply call the propertiesOf function of any object by passing another object as the argument. It returns an object which has similar keys linked to each other.
The above example will result in:
{a: "b", b: "d"}
It seems you want something like this: make a function that finds all the keys in the 2nd object that have a given value. Then pass the value from the first object to that function.
obj1={a:1,b:2,c:3,d:4};
obj2={a:2,b:5,c:3,d:4};
function findKeysByValue(obj, v) {
var results = [];
for (var k in obj) {
if (obj.hasOwnProperty(k) && v == obj[k]) {
results.push(k);
}
}
return results;
}
console.log(findKeysByValue(obj2, obj1['b'])); // ['a']

removing the key from a key value pair of objects in javascript

Let's say I have this Array of objects:
[300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} ...]
I have that kind of object and I am iterating using recursive function, and there's no way I will change my counter to start at 300, I always start at 0.
I am thinking of a solution, to remove the keys from the agrray so that I will have an array like so:
[{a:"some", b:"value"}, {a: "another", b: "val"} ...]
How do I do that in javascript? Also, if there is another way that would be much faster than creatng a function that will remove keys, it will be much better.
This will give you a syntax error (SyntaxError: missing ] after element list):
var data = [300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}];
You mean this:
var data = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}};
And to convert that into an array, loop over the object and push each value into a new array:
var arr = [];
for (var k in data) {
arr.push(data[k]);
}
Fiddle
If you meant that the initial structure of array is this:
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
then this should work (result array):
var result = [];
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
for(var i =0; i < data.length; i++){
for(var key in data[i]) {
if(data[i].hasOwnProperty(key)) {
result.push(data[i][key]);
break;
}
}
}
There is a point here that should be clarified. When you have a Array object which its values starts from 300 as its indexes, it means you have 300 indexes with undefined values, but if it is just an Array-like object it could be totally different.
Let's say this is not an Array-like and is an actual Array, so you have to filter it so that all the undefined values get removed from your array, so your array should be like:
var arr = [/*0*/undefined, ..,/*299*/undefined, /*300*/{a:"some", b:"value"}, /*301*/ {a: "another", b: "val"} ...]
var result = arr.filter(function(value,index){
return (value !== undefined);
});
but what you have mentioned in your question, is more likely a javascript object, so to do what you want you can do:
var myObj = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} };
var result = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
result.push(obj[key]);
}
}
in this for loop hasOwnProperty function helps you make sure if it is one of the actual object values, and not other possible keys from the object's prototype chain.

Categories

Resources