Javascript: Map iterate object keys and values - javascript

Trying to get both key and value using the following script
jsonData = {"jurisdiction":"SCPB - LON","firstName":"David Dynamic"}
var keys = Object.keys(jsonData).map(function(keys, values) {
logInfo(jsonData[keys], jsonData[values]);
});
returns just the values:
2022-08-30 18:29:49 David Dynamic undefined
2022-08-30 18:29:49 SCPB - LON undefined
How can I get both? the js engine is spiderMonkey 1.8

Object.keys(jsonData).forEach(function(key) {
logInfo(key, jsonData[key]);
});
Object.keys documentation
Or as suggested by Kondrak Linkowski:
Object.entries(jsonData).forEach(([key, value]) => logInfo(key, value))

You likely want to use Object.entries to get the keys and values of the object.
If you want to do it with Object.keys, as in your example, you can modify it like this: (logging the key, and the value at this key)
const jsonData = {
foo: 'bar',
fizz: 'fuzz',
}
const logInfo = console.log
var keys = Object.keys(jsonData).map(function(key) {
logInfo(key, jsonData[key]);
});

Related

Get object values without using Object.values()

I just started learning to code and am working on this challenge. Having issues finding any relevant guidance online. Thanks in advance.
function keys(json) {
var obj = JSON.parse(json);
let result = [];
for (const key in obj) {
result.push(key);
}
return result;
}
I got this to work for returning keys without using Object.keys and I sort of assumed I could just swap the 'key' for 'value' but that didn't work.
function keys(json) {
var obj = JSON.parse(json);
var values = Object.keys(obj).map((key,value)=>{ values.push(value) });
return values;
}
Also tried this, but I don't really understand the map function yet.
Is this what you are looking for?
const obj = {a:3, b:4}
const result = []
for (const key in obj) {
result.push(obj[key])
}
console.log(result)
With Object.keys you get an array of keys (own, enummerable) of the array. for mapping values, you need to take a property accessor with object and key.
function values(json) {
const object = JSON.parse(json);
return Object
.keys(object)
.map(key => object[key]);
}
console.log(values('{"foo":"bar","baz":42}'));

Javascript: Convert a JSON string into ES6 map or other to preserve the order of keys

Is there a native (built in) in ES6 (or subsequent versions), Javascript or in TypeScript method to convert a JSON string to ES6 map OR a self-made parser to be implemented is the option? The goal is to preserve the order of the keys of the JSON string-encoded object.
Note: I deliberately don't use the word "parse" to avoid converting a JSON string first to ECMA script / JavaScript object which by definition has no order of its keys.
For example:
{"b": "bar", "a": "foo" } // <-- This is how the JSON string looks
I need:
{ b: "bar", a: "foo" } // <-- desired (map version of it)
UPDATE
https://jsbin.com/kiqeneluzi/1/edit?js,console
The only thing that I do differently is to get the keys with regex to maintain the order
let j = "{\"b\": \"bar\", \"a\": \"foo\", \"1\": \"value\"}"
let js = JSON.parse(j)
// Get the keys and maintain the order
let myRegex = /\"([^"]+)":/g;
let keys = []
while ((m = myRegex.exec(j)) !== null) {
keys.push(m[1])
}
// Transform each key to an object
let res = keys.reduce(function (acc, curr) {
acc.push({
[curr]: js[curr]
});
return acc
}, []);
console.log(res)
ORIGINAL
If I understand what you're trying to achieve for option 2. Here's what I came up with.
https://jsbin.com/pocisocoya/1/edit?js,console
let j = "{\"b\": \"bar\", \"a\": \"foo\"}"
let js = JSON.parse(j)
let res = Object.keys(js).reduce(function (acc, curr) {
acc.push({
[curr]: js[curr]
});
return acc
}, []);
console.log(res)
Basically get all the keys of the object, and then reduce it. What the reducer function convert each keys to an object
function jsonToMap(jsonStr) {
return new Map(JSON.parse(jsonStr));
}
More details : http://2ality.com/2015/08/es6-map-json.html
use for in loop
let map = new Map();
let jsonObj = {a:'a',b:'b',c:'c'}
for (let i in jsonObj){
map.set(i,jsonObj[i]);
}
btw, i saw the comment below and i think map is not ordered because you use key to achieve data in map, not the index.

Why does a js map on an array modify the original array?

I'm quite confused by the behavior of map().
I have an array of objects like this:
const products = [{
...,
'productType' = 'premium',
...
}, ...]
And I'm passing this array to a function that should return the same array but with all product made free:
[{
...,
'productType' = 'free',
...
}, ...]
The function is:
const freeProduct = function(products){
return products.map(x => x.productType = "free")
}
Which returns the following array:
["free", "free", ...]
So I rewrote my function to be:
const freeProduct = function(products){
return products.map(x => {x.productType = "free"; return x})
}
Which returns the array as intended.
BUT ! And that's the moment where I loose my mind, in both cases my original products array is modified.
Documentation around map() says that it shouldn't ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ).
I even tried to create a clone of my array turning my function into this:
const freeProduct = function(products){
p = products.splice()
return p.map(x => {x.productType = "free"; return x})
}
But I still get the same result (which starts to drive me crazy).
I would be very thankful to anyone who can explain me what I'm doing wrong!
Thank you.
You're not modifying your original array. You're modifying the objects in the array. If you want to avoid mutating the objects in your array, you can use Object.assign to create a new object with the original's properties plus any changes you need:
const freeProduct = function(products) {
return products.map(x => {
return Object.assign({}, x, {
productType: "free"
});
});
};
2018 Edit:
In most browsers you can now use the object spread syntax instead of Object.assign to accomplish this:
const freeProduct = function(products) {
return products.map(x => {
return {
...x,
productType: "free"
};
});
};
To elaborate on SimpleJ's answer - if you were to === the two arrays, you would find that they would not be equal (not same address in memory) confirming that the mapped array is in fact a new array. The issue is that you're returning a new array, that is full of references to the SAME objects in the original array (it's not returning new object literals, it's returning references to the same object). So you need to be creating new objects that are copies of the old objects - ie, w/ the Object.assign example given by SimpleJ.
Unfortunately, whether the spread operator nor the object assign operator does a deep copy.... You need to use a lodash like function to get areal copy not just a reference copy.
const util = require('util');
const print = (...val) => {
console.log(util.inspect(val, false, null, false /* enable colors */));
};
const _ = require('lodash');
const obj1 = {foo:{bar:[{foo:3}]}};
const obj2 = {foo:{bar:[{foo:3}]}};
const array = [obj1, obj2];
const objAssignCopy = x => { return Object.assign({}, x, {})};
const spreadCopy = x => { return {...x}};
const _Copy = x => _.cloneDeep(x);
const map1 = array.map(objAssignCopy);
const map2 = array.map(spreadCopy);
const map3 = array.map(_Copy);
print('map1', map1);
print('map2', map2);
print('map3', map3);
obj2.foo.bar[0].foo = "foobar";
print('map1 after manipulation of obj2', map1); // value changed
print('map2 after manipulation of obj2', map2); // value changed
print('map3 after manipulation of obj2', map3); // value hasn't changed!
Array Iterator Array.map() creates the new array with the same number of elements or does not change the original array. There might be the problem with referencing if there is object inside the array as it copies the same reference, so, when you are making any changes on the property of the object it will change the original value of the element which holds the same reference.
The solution would be to copy the object, well, array.Splice() and [...array](spread Operator) would not help in this case, you can use JavaScript Utility library like Loadash or just use below mention code:
const newList = JSON.parse(JSON.stringify(orinalArr))
Array Destructuring assignment can be used to clone the object.
const freeProduct = function(products){
p = products.splice()
return p.map(({...x}) => {x.productType = "free"; return x})
}
This method will not modify the original object.

Convert Object to 2D array in JavaScript

Can we convert an Object to a 2D Array,
My Object is like this
So That Array Key will be like 'STARS_2' and value is ["STARS_4", "STARS_0", "STARS_12"]
with My attempts I can get something like this,
With this Code,
var testArray =[];
_.map(childFieldNames, function (value, key) {
var newArray = new Array();
newArray[key] = value;
testArray.push(newArray);
});
Here Keys are actually another array, which I do not want. I want key should be like 'STARS_2' , i.e. property of master object.
Is this what you need?
var ary2D = Object.keys(childFieldNames).map(function (key) {
return childFieldNames[key];
});
better version for what Shilly showed would be:
const arr2D = Object.values(childFieldNames);
Object.entries(obj)
E.g.
const objVariable = {name: "Ted", job: "Dentist"}
const 2dArray = Object.entries(objVariable)
console.log(2dArray) // will print [["name", "Ted"], ["job", "Dentist"]]
Object.entries is a static method that belongs to the Object class. As a parameter, it accepts an object and returns a two-dimensional array.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
You don’t need to create your structure into 2D array to just iterate over each key and its respective value(which is an array). If you want to iterate over it you can do something like this.
const object = {
a: [1,2,3],
b: [2,3,5]
};
for (const [key, value] of Object.entries(object)) {
value.forEach(v=>{
console.log(`${key}: ${v}`);
})
}

Mootools convert Hash to array

I have Hash obj:
var obj = {a,b,c,...};
obj = $H(obj);
I need to convert it to simple array
[a,b,c,..]
How can I do?
Thx.
Object.getValues(myObject) to get an Array of all values.
Object.getKeys(myObject) to get an Array of keys.
For 1.2 simply, Hash provides the same methods.
And don't use Objects {} to store lists like in your example. Arrays are for lists, Objects are for associative arrays.
EDIT:
Since version 1.3 Object.getValues and Object.getKeys has been deprecated and replaced by Object.keys resp Object.values.
since you use $H I am assuming older ver of mootools, 1.2.x since it got deprecated in 1.3 in favour of the new Object. construct
The hash had a .each method:
var Hobj = $H({
tool: "bar",
ghost: "goblin"
});
var arr = [];
Hobj.each(function(value, key) {
arr.push(value); // what to do with key?
});
console.log(arr);
an alternative that grabs the complete objects with their keys but not as array keys:
Hobj.each(function(value, key) {
var obj = {};
obj[key] = value;
arr.push(obj);
});
Assuming you want the values in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(obj[prop]);
}
}
If you want the property names to be in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(prop);
}
}
the hasOwnProperty call is important because it will filter out inherited functions and private members of the mooTools hash class that you don't probably want in your resulting array

Categories

Resources