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.
Related
Consider the following code:
a = {};
a['a'] = 1;
a['b'] = 3;
a['c'] = 5;
a['d'] = 2;
b = [];
b['a'] = 1;
b['b'] = 3;
b['c'] = 5;
b['d'] = 2;
console.log(typeof a, typeof b);
console.log(a);
console.log(b);
And the output console.log is as follow:
object object
{ a: 1, b: 3, c: 5, d: 2 }
[ a: 1, b: 3, c: 5, d: 2 ]
Granted that they are of both type object, to my understanding, a is an object of key:value pairs, where as b is an array of [key:value] pairs. Is that the right assumption?
And aside from a for(index in array) pattern of looping, where I have to use the iterator index to grab the value (array[index]), is there a better, more simple method of looping through these key/value pairs to grab the index/value or to just process the data at each index, sort of like map or reduce for arrays?
One such problem I ran into was, if I wanted to grab the key with the least count (in the above examples, it would be 'a'), is there a way to do it without using the for( index in array) pattern?
In Javascript arrays are objects, so you can add keys like you are doing in your example above, but this is not the normal way to use arrays and will probably confuse a lot of people looking at your code. There are occasional when it's useful to add a property to an array, but using them just as key stores definitely not the norm.
If you want an ordered collections with numeric indexes, use an array:
let arr = []
arr.push(10)
arr.push(20)
console.log(arr)
console.log(arr[0])
If you want properties where order isn't important and you will have string keys, use an object. In the above example you are using both types like objects — there's no reason to use an array like that.
Having said that if you want an iterator of values from an object, you can use Object.values(). This delivers an array of values from an object if you only want to process the values:
a = {};
a['a'] = 1;
a['b'] = 3;
a['c'] = 5;
a['d'] = 2;
console.log(Object.values(a))
// process them
let newArr = Object.values(a).map(n => n * 10)
console.log(newArr)
Object.entries is also useful — it returns an array of key/value pairs, which, with reduce() makes a nice way to find the minimum:
a = {
a: 1,
b: 3,
c: 5,
d: 2
};
// current will be an array of the form [key, value]
let [minKey, minValue] = Object.entries(a).reduce((min, current) => min[1] < current[1] ? min : current)
console.log(minKey, minValue)
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"
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}
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; }
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']