For example, the array is:
chipsArray = [{'cheetos':'good'},{'dorritos':'better'}]
Here, chipsArray[0] would give me {'cheetos':'good'}. Let's say I populated this array like the following:
chipsArray.push({[chips]:quality})
But now that I'm trying to access the cheetos or dorritos keys in each of objects in this array, I can't. Doing chipsArray[0].chips gives me undefined.
As far as I know when populating the key of an object with a certain value/variable, they should be wrapped in square braces. But how can we extract values from them later on when each of these objects are array indices like the example given above? I tried using Object.keys(chipsArray[index]), but this only gives me the keys whereas I'm trying to extract the specific value for that specific key.
Tl;Dr: How to extract the key of an object inside an array when the keys are strings like this:
chipsArray = [{'cheetos':'good'},{'dorritos':'better'}]
You could use Object.keys and get only the first element.
var chipsArray = [{ cheetos: 'good' }, { dorritos: 'better' }];
chipsArray.forEach(function (object) {
var key = Object.keys(object)[0];
console.log(key, object[key]);
});
Or create an object with the reference to the single objects
var chipsArray = [{ cheetos: 'good' }, { dorritos: 'better' }],
hash = Object.create(null);
chipsArray.forEach(function (object) {
hash[Object.keys(object)[0]] = object;
});
console.log(hash['dorritos']['dorritos']);
Use the following function. It returns the value by key in the array
function getItemByKey (key, array) {
var value;
array.some(function (obj) {
if (obj[key]) {
value = obj[key];
return true;
}
return false;
});
return value;
}
More about Array.prototype.some here
I think the easiest way is to access the value:
Object.values(chipsArray[i])
where i is the index of the array.
Output:
> chipsArray = [{'cheetos':'good'},{'dorritos':'better'}]
[ { cheetos: 'good' }, { dorritos: 'better' } ]
> Object.values(chipsArray[0])
[ 'good' ]
Related
I am trying to merge some JSON data sets BY key value WHILE including duplicate values WHERE the key matches.
I have tried this quite a bit now but can't seem to produce the object that I need.
Object 1
[
{"userId":"1",
"email":"email1#gmail.com"
},
{"userId":"2",
"email":"email2#gmail.com"
}
]
Object 2
[
{"id":"1abc",
"listingId":"4def",
"userId":"2"
},
{"id":"2abc",
"listingId":"2def",
"userId":"1"
},
{"id":"3abc",
"listingId":"3def",
"userId":"2"
}
]
I need to merge these objects in a way that looks like this:
Desired Output
[
{"id":"1abc",
"listingId":"4def",
"userId":"2",
"email":"email2#gmail.com"
},
{"id":"2abc",
"listingId":"2def",
"userId":"1",
"email":"email1#gmail.com"
},
{"id":"3abc",
"listingId":"3def",
"userId":"2",
"email":"email2#gmail.com"
}
]
Problems I am Experiencing
I am able to merge the data sets successfully using a function that looks like this:
function merge(a, b, key) {
function x(a) {
a.forEach(function (b) {
if (!(b[key] in obj)) {
obj[b[key]] = obj[b[key]] || {};
array.push(obj[b[key]]);
}
Object.keys(b).forEach(function (k) {
obj[b[key]][k] = b[k];
});
});
}
var array = [],
obj = {};
x(a);
x(b);
return array;
}
https://stackoverflow.com/a/35094948/1951144
But it produces results that look like this:
[
{"id":"1abc",
"listingId":"4def",
"userId":"2",
"email":"email2#gmail.com"
},
{"id":"2abc",
"listingId":"2def",
"userId":"1",
"email":"email1#gmail.com"
}
]
Is there a way to use the above function WHILE keeping AND including the duplicate values where my keys match?
For each element in arr2, create a new element containing the props of the item from arr2, and the email of the corresponding entry in arr1.
let arr1 = [
{"userId":"1",
"email":"email1#gmail.com"
},
{"userId":"2",
"email":"email2#gmail.com"
}
];
let arr2 = [
{"id":"1abc",
"listingId":"4def",
"userId":"2"
},
{"id":"2abc",
"listingId":"2def",
"userId":"1"
},
{"id":"3abc",
"listingId":"3def",
"userId":"2"
}
];
let output = arr2.map(a2 => ({...a2, email: arr1.find(a1 => a1.userId === a2.userId)?.email}));
console.log(output);
This solution works even if the key isn't known yet. .flatMap() both arrays and pass in the desired key (in example it's "userId"). Use Object.entries() on each object so they will be an array of pairs.
[{A1: A1v}, {A2: A2v},...]
// into
[[A1, A1v], [A2, A2v],...]
.flatMap() the second array and on each iteration .flatMap() the first array. Then compare the given key ("userID") with the key of each object from the second array ("a") AND the value of that key and the value of the key of the object in the first array.
a === key && av === bv
If both criteria are meet then merge those objects and return it, otherwise...
? {...objA, ...objB}
return an empty array, which ultimately results to nothing since .flatMap() flattens one level of arrays.
: []
const arrA=[{userId:"1",email:"email1#gmail.com"},{userId:"2",email:"email2#gmail.com"}];const arrB=[{id:"1abc",listingId:"4def",userId:"2"},{id:"2abc",listingId:"2def",userId:"1"},{id:"3abc",listingId:"3def",userId:"2"}];
function masterKey(primary, key, secondary) {
let result = secondary.flatMap(objB => Object.entries(objB).flatMap(([b, bv]) =>
primary.flatMap(objA => Object.entries(objA).flatMap(([a, av]) =>
a === key && av === bv ? {...objA, ...objB} : []))));
return result;
}
console.log(masterKey(arrA, "userId", arrB));
For Example :
I have an object and in that object, I have values in the array. I want to return the array which contains the key which contains the value passing as a variable.
function getValues(val , object){
return []; // return [b,c] because xyz are present in both
}
var object = {
"a" : ["abc", "cde","efg"],
"b" : ["asdf","asee","xyz"],
"c" : ["asaw","wewe","xyz"]
getValues("xyz", object);
}```
There are various ways to approach this.
One could be using Object's native functions:
function getValues(str, obj) {
return Object
// returns the entries pairs in a array of [key, value]
.entries(obj)
// from the array it searches the value for the string inputted and maps it back
.map(([key, array]) => array.includes(str) ? key : undefined)
// simply remove the undefined returned values from map()
.filter((value) => value);
};
This could have been done with reduce() as well but I found it easier to explain this way.
Another approach is using a for loop to iterate over the keys of the object:
function getValues(str, obj) {
let arr = [];
// Iterates through the object selecting its keys
for (let key in obj) {
// If the array of the current key has the string in it, includes in the array
if (obj[key].includes(str)) {
arr.push(key)
}
}
return arr;
}
I am trying to filter an object with another object inside of an array.
To be more precise, I am trying to compare the keys of the object inside the array, to the keys of my main object. If the values are the same, I want to return the value corresponding to those keys.
Here's an example:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
}]
I wanna check if any of the keys in object b are inside object a and if they are, I want to return their value into array. For example, I want to return ["A++","D","C+"]
I've tried using filter and Array.prototype.some but I couldn't figure out anything. Any advice on how should I achieve this?
First make an array or Set of all the keys inside b, then use .map to access each key on the a object:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
}];
const keys = b.flatMap(Object.keys);
const arr = keys.map(key => a[key]);
console.log(arr);
I'm assuming that you want to handle multiple objects in b.
If so and if you want one array for each object in b then you could do something like:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
},{
"maths":"Mathematics",
"biology":"Biology",
"english":"English"
}]
const result = b.map(obj => Object.keys(obj).map(key => a[key]));
console.log(result);
If you are dealing with a single object in the array b, then you can do this:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
}]
const valuesInAndB = Object.keys(a).reduce((acc,x) => {
if (b[0][x]) {
return acc.concat(a[x]);
}
return acc;
}, []);
console.log(valuesInAndB);
However, if the objects in b will be greater than one then as answered by #certainperformance you could get all the keys in b and map through a with those keys.
const keysInB = b.flatMap(Object.keys);
keysInB.map(key => a[key]);
flatMap is not available in some older browsers, please keep that in mind.
I have some problem with sorting items inside object. So I have something like this:
var someObject = {
'type1': 'abc',
'type2': 'gty',
'type3': 'qwe',
'type4': 'bbvdd',
'type5': 'zxczvdf'
};
I want to sort someObject by value, and this is where I have problem.
I have sorting function that should return key/value pairs sorted by value:
function SortObject(passedObject) {
var values = [];
var sorted_obj = {};
for (var key in passedObject) {
if (passedObject.hasOwnProperty(key)) {
values.push(passedObject[key]);
}
}
// sort keys
values.sort();
// create new object based on Sorted Keys
jQuery.each(values, function (i, value) {
var key = GetKey(passedObject, value);
sorted_obj[key] = value;
});
return sorted_obj;
}
and function to get key:
function GetKey(someObject, value) {
for (var key in someObject) {
if (someObject[key] === value) {
return key;
}
}
}
The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)
Does anyone know how to sort items in object?
Plain objects don't have order at all. Arrays -that are a special types of objects- have.
The most close thing that you can have is an array with the object values sorted . Something like, for example:
_valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
You have two possibilities:
Refactor your object into an array
Something like this:
var myObj = [
['type1', 'abc'],
['type2', 'gty'],
...
];
Or even better, since using it somewhere would not rely on array positions but full named keys:
var myObj = [
{name: 'type1', val:'abc'},
{name: 'type2', val:'gty'},
...
];
Use your object with an auxiliar array
Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object
var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
key = ordKeys[i]
alert(key + " - " + myObj[key]);
}
Combination of both of them
If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.
EDIT
You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.
I need to create object in javascript that allows to fetch values using keys & also iterate over keys. The primary requirement is fetching value by key but iteration is required to maintain sort order of entries by values(integer).
How do I go about creating such an object ?
sampleJson={
"1":"john",
"2":"johny"
}
You can iterate using for in loop
for(key in sampleJson){
//ur code
}
All objects in JavaScript are JSONeable! (is that really a word).
All objects in JavaScript are a collection of key value mappings.
A for in loop iterates over the keys of an object.
Native objects don't support exactly what you're looking for, but it's fairly straightforward to create a wrapper around native objects that provides extra functionality.
A possible approach:
function KeySortArr(obj) {
this.obj = obj || {};
}
KeySortArr.prototype = {
get: function(key) {
return this.obj[key];
},
set: function(key, value) {
this.obj[key] = value;
},
keys: function() {
var keys = [];
for(var i in this.obj) {
if (this.obj.hasOwnProperty(i))
keys.push(i);
}
return keys;
},
getKeysSortedByValue: function() {
var obj = this.obj;
return this.keys().sort(function(a, b) {
return obj[a] > obj[b];
});
}
};
Usage:
var arr = new KeySortArr();
arr.set("test", 4);
arr.set("another", 2);
arr.set("ok", 60);
arr.set("last", 14);
The following then:
arr.getKeysSortedByValue();
Returns:
["another, "test", "last", "ok"]
In other words, the keys are sorted by their associated value. This might not be exactly what you were looking for, but it should be close.