Objects vs arrays in Javascript for key/value pairs
Each solution has its use cases.
I think the first solution is good if you're trying to define a one-to-one relationship (such as a simple mapping), especially if you need to use the key as a lookup key.
The second solution feels the most robust to me in general, and I'd probably use it if I didn't need a fast lookup key:
- It's self-describing, so you don't
have to depend on anyone using
people to know that the key is the id of the user. - Each object comes self-contained,
which is better for passing the data
elsewhere - instead of two parameters
(id and name) you just pass around
people. - This is a rare problem, but sometimes
the key values may not be valid to
use as keys. For example, I once
wanted to map string conversions
(e.g., ":" to ">"), but since ":"
isn't a valid variable name I had to
use the second method. - It's easily extensible, in case
somewhere along the line you need to
add more data to some (or all) users.
(Sorry, I know about your "for
argument's sake" but this is an
important aspect.)
Javascript: object key-value pairs
The method you are using just overrides the duplicate keys you created ... to prevent this situation do not use object keys ! you can rely on the arrays passing the data you want
See example =>
const myObject = {
// number : [name , option]
0: ["small", 1],
1: ["medium", 1]
};
let item = [];
Object.entries(myObject).forEach(obj => {
item.push({
name: obj[1][0],
option_id: obj[1][1]
});
})
console.log(item);
Best way using array methodslet myObject = [
["small", 1],
["medium", 1]
];
myObject = myObject.map(obj => {
return {
name: obj[0], option_id: obj[1]};
});
console.log(myObject);
Concise way to check an array of objects for a key/value pair?
Below code outputs a boolean. true if all ids are available in array2
var array1 = [
'j2n4k2j3n42k3j4n',
"l2nkj2n3k4bj",
'ln23jk4n2njknn2n'
]
var array2 = [{
fruit: "banana",
origin: "florida",
id: "j2n4k2j3n42k3j4n",
},
{
fruit: "peach",
origin: "georgia",
id: "l2nkj2n3k4bj"
},
]
const results = array1.every(id => array2.find(item => item.id === id))
console.log(results)
Create an object with key-value pairs from an array
You can use Object.keys to read the name of the key and use the 3rd parameter of array.reduce to get the index of currently processed item.
const myArray = [{value: "test"}, {value: "abc"}, {value: "xyz"}];
//the desired result is this: result = { "value1": "test", "value2": "abc", "value3": "xyz" };
const result = myArray.reduce((agg, item, index) => {
agg[Object.keys(item)[0] + (index + 1)] = item.value;
return agg;
}, {})
console.log(result);
Iterate over objects and return key-value pairs from an array in Javascript
Okay, So after spending some time on basics I realized it was quite straightforward.
Learnings:
- Move the incoming backend response out from consumeAPI()
- Pop-out values of each object from it.
- Return the Object to calculatePlot() function.
function consumeAPI() {
const value = sample_graphs.pop();
const x_1 = value.quadrant1_x;
const y_1 = value.quadrant1_y;
const x_2 = value.quadrant2_x;
const y_2 = value.quadrant2_y;
const x_3 = value.quadrant3_x;
const y_3 = value.quadrant3_y;
const x_4 = value.quadrant4_x;
const y_4 = value.quadrant4_y;
let retObj = {
x1: x_1 * range,
y1: y_1 * range,
x2: x_2 * range,
y2: y_2 * range,
x3: x_3 * range,
y3: y_3 * range,
x4: x_4 * range,
y4: y_4 * range,
};
return retObj;
}
Rest remains the same. function generateRandomUser() {
const user = consumeAPI();
return calculatePlot(user);
}
let sample_graph = [
{
quadrant1_x: "0.17",
quadrant2_x: "0.53",
quadrant3_x: "-0.48",
quadrant4_x: "-0.86",
quadrant1_y: "0.31",
quadrant2_y: "-0.21",
quadrant3_y: "-0.60",
quadrant4_y: "0.50",
},
...
];
// consumeAPI() goes here
for (let i = 0; i < maxUsers; i++) {
let plot = generateRandomUser();
addUser(plot);
calculateMidPoint(plot);
}
Sample: JSFiddle Convert key value pair to array of objects
There exists a method Object.entries
that turns object into list of keys and values already, mapping it to match your required format should not be difficult.
const data = {good: 'value1', key2: 'value2', key3: 'value3'};
const result = Object.entries(data).map(([key, value]) => ({key, value}))
console.log(result)
How to match objects with the same key-value pairs passed as arguments?
You could create a simple implementation using Object.keys()
and Array.every()
.
This means each returned item must include each key and value from the source, but may include extra keys and values:
function whatIsInAName(collection, source) {
return collection.filter(obj => Object.keys(source).every(key => obj[key] === source[key]));
}
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}));
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 2, "c": 3}));
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3, "d": 4 }], {"a": 1, "b": 2, "c": 3}));
console.log(whatIsInAName([{"a": 1, "c": 3, "d": 4 }], {"a": 1, "b": 2, "c": 3}));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Topics
Differencebetween Native Objects and Host Objects
How to Use a Link to Call JavaScript
Js/Es6: Destructuring of Undefined
Is Localstorage.Getitem('Item') Better Than Localstorage.Item or Localstorage['Item']
JavaScript Switch VS. If...Else If...Else
Resize Jqgrid When Browser Is Resized
How to Upload Preview Image Before Upload Through JavaScript
How to Getting Browser Current Locale Preference Using JavaScript
How to Use Local Storage in Angular
How to Reset the Scale/Zoom of a Web App on an Orientation Change on the Iphone
Mongoose, Select a Specific Field with Find
How to Calculate the Number of Years Between Two Dates
Load "Vanilla" JavaScript Libraries into Node.Js
Why Is There a 'Null' Value in JavaScript
What's "This" in JavaScript Onclick
Jquery Smooth Scroll to an Anchor
How to Find a Reason Angularjs "Argument 'Myctrl' Is Not a Function, Got Undefined"