JavaScript: Convert array of objects into hashmap - javascript

I have a set of values in an array where each value has an ID and LABEL.
Once I have the value array and type console value[0] and value[1], the output is:
value[0]
Object {ID: 0, LABEL: turbo}
value[1]
Object {ID: 1, LABEL: classic}
How can I store these values in a hash map like a key-value (ID-LABEL) pair, and store them in a json?

This could be achieved by calling reduce on your array of values (ie data), to obtain the required hash map (where ID is the key and value is the corresponding LABEL):
const data = [
{ID: 0, LABEL: 'turbo'},
{ID: 1, LABEL: 'classic'},
{ID: 7, LABEL: 'unknown'}
];
const hashMap = data.reduce((result, item) => {
return { ...result, [ item.ID ] : item.LABEL };
}, {});
const hashMapJson = JSON.stringify(hashMap);
console.log('hashMap', hashMap);
console.log('hashMapJson', hashMapJson);
/*
More concise syntax:
console.log(data.reduce((result, { ID, LABEL }) => ({ ...result, [ ID ] : LABEL }), {}))
*/

Try (where h={})
data.map(x=> h[x.ID]=x.LABEL );
const data = [
{ID: 0, LABEL: 'turbo'},
{ID: 1, LABEL: 'classic'},
{ID: 3, LABEL: 'abc'}
];
let h={}
data.map(x=> h[x.ID]=x.LABEL );
console.log(h);

You can iterator over each item in the array, and use the ID proeprty as a javascript objects key and the LABEL as the value.
var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}];
let theNewMap = {};
for(var i = 0; i < value.length; i++) {
theNewMap[value[i].ID] = value[i].LABEL;
}
// theNewMap Should now be a map with 'id' as key, and 'label' as value
console.log(JSON.stringify(theNewMap ))

You can use forEach method.
> var hmap = {};
undefined
> var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}]
undefined
> value.forEach(function(element){
... hmap[element.ID] = element.LABEL;
... });
> hmap
{ '0': 'turbo', '1': 'classic' }
or
var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}]
var hmap = {};
value.forEach(function(element){
hmap[element.ID] = element.LABEL;
});
console.log(hmap);

Related

How to group array of object by key value pairs using javaScript?

I just started learning JavaScript, I have this type of array, how I can turn this array of objects into key-value pairs like below, Any source and reference is acceptable.
Sample Array:
[
{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},
{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}
]
Expected Result:
{
"6d7e75e6-c58b-11e7-95-ac162d77eceb":1,
"6d2e75e6-c58b-11e7-95-ac162d77eceb":1
}
Using Array.prototype.Reduce:
const arr = [{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}];
const result = arr.reduce((acc, { Id, qty }) => ({ ...acc, [Id]: qty }), {});
console.log(result);
Another approach, a little more beginner friendly.
const arr = [
{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},
{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}
];
const newObject = {}; // empty object
// loop over each element of the array
arr.forEach(element => {
// the key is the element identifier (Id) and the value is the element quantity (qty)
newObject[element.Id] = element.qty;
});
You can use a loop and add the item.Id as the key and the item.qty as the value in an empty object.
let arr = [{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}]
let obj = {}
arr.forEach(item => {
obj[item.Id] = item.qty
})
console.log(obj)
You can easily achieve this result using forEach in a single line of code.
const arr = [
{ Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 },
{ Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 },
];
const result = {};
arr.forEach(({ Id, qty }) => (result[Id] = qty));
console.log(result);
You can achieve the desired result with below code
//input array
const arrList = [
{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},
{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}
]
function findArray(arr) {
//define a new array to store Id's
let newArray = [];
//iterate through array items
arr.forEach(item => {
newArray.push(item.Id);
});
return newArray;
}
//call findArray function to get desired output
console.log(findArray(arrList));
Using Object.fromEntries()
const
array = [{ Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }, { Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }],
object = Object.fromEntries(array.map(({ Id, qty }) => [Id, qty]));
console.log(object);
or, for some fragile novelty...
const
array = [{ Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }, { Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }],
object = Object.fromEntries(array.map(Object.values));
console.log(object);

Compare two javascript array of objects and merge data

I'm having a bad time comparing two array of objects on a key.
I would like to compare, substract value when the key matches and display negative value when not in my target array. Finally, I want to have all target objects (if key didn't match) inside my final array.
An exemple would save 1000 words :
const initial = [{id: 1, value: 47}, {id: 2, value: 20}, {id: 7, value: 13}];
const target = [{id: 1, value: 150}, {id: 3, value: 70}, {id: 40, value: 477}];
//Desired output
// [{id: 1, value: 103}, {id: 2, value: -20}, {id: 7, value: -13}, {id: 3, value: 70}, {id: 40, value: 477}];
let comparator = [];
initial.map(initia => {
let hasSame = target.find(targ => {
return initia.id === targ.id
});
if(hasSame){
initia.value -= hasSame.value
} else{
initia.value = -initia.value
}
});
console.log(initial);
I'm getting almost the result I want except that I don't know how to merge target values properly. Is it possible to merge this values without looping over target array once more? Or could I do that inside the find ?
I want to get advice to do this as clean as possible
Thanks you!
You could use a Map and collect same id with a wanted factor for summing.
As result take key/value as new properties.
var add = (map, factor) => ({ id, value }) => map.set(id, map.has(id)
? map.get(id) - value * factor
: value * factor
),
initial = [ {id: 1, value: 47 }, { id: 2, value: 20 }, { id: 7, value: 13 }],
target = [{ id: 1, value: 150 }, { id: 3, value: 70 }, { id: 40, value: 477 }],
map = new Map,
result;
initial.forEach(add(map, -1));
target.forEach(add(map, 1));
result = Array.from(map, ([id, value]) => ({ id, value }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If the intent is to avoid a nested find inside of the loop, you could reduce the two arrays in to a Set. They don't allow duplicate keys, so you would ensure a single value for each ID provided.
const valueSet = [...initial, ...target].reduce((total, obj) => {
total[obj.id] = !total[obj.id]
? -obj.value
: total[obj.id] -= obj.value
return total;
}, {});
const result = Object.keys(valueSet).map(key => ({ id: key, value: valueSet[key]}))
console.log(result);
Then you'd map back over the result to build out the intended array.

merge array with unique keys

I have array of objects called newArray and oldArray.
Like this : [{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}]
example :
newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]
oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]
result will be = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]},
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}
];
I wanted to merge both the array in such a way that whenever name and label are equal in both the arrays it should only consider newArray value.
I have tried
function mergeArrayWithLatestData (newData, oldData) {
let arr = [];
let i = 0; let j =0
while ((i < newData.length) && (j < oldData.length)) {
if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1) {
arr.push(newData[i])
} else {
arr.push(newData[i]);
arr.push(oldData[i]);
}
i += 1;
j += 1;
}
while (i < newData.length) {
arr.push(newData[i]);
}
return arr;
}
But i am not getting correct result.
Any suggestions?
You could add all array with a check if name/label pairs have been inserted before with a Set.
var newArray = [{ name: 'abc', label: 'abclabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4] }],
oldArray = [{ name: 'oldArray', label: 'oldArrayLabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4, 5] }],
result = [newArray, oldArray].reduce((s => (r, a) => {
a.forEach(o => {
var key = [o.name, o.label].join('|');
if (!s.has(key)) {
r.push(o);
s.add(key);
}
});
return r;
})(new Set), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can simply use Array.reduce() to create a map of the old Array and group by combination of name and label. Than iterate over all the elements or objects of the new Array and check if the map contains an entry with given key(combination of name and label), if it contains than simply update it values with the values of new array object, else add it to the map. Object.values() on the map will give you the desired result.
let newArray = [ {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4]} ];
let oldArray = [ {name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4,5]} ];
let map = oldArray.reduce((a,curr)=>{
a[curr.name +"_" + curr.label] = curr;
return a;
},{});
newArray.forEach((o)=> {
if(map[o.name +"_" + o.label])
map[o.name +"_" + o.label].values = o.values;
else
map[o.name +"_" + o.label] = o;
});
console.log(Object.values(map));
In your first while loop
while ((i < newData.length) && (j < oldData.length)) {
if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1)
{
arr.push(newData[i])
} else {
arr.push(newData[i]);
arr.push(oldData[i]);
}
i += 1;
j += 1;
}
i and j always have the same value, you are only comparing entries at the same positions in the arrays. If they have different lengths, you stop comparing after the shorter array ends. Your second while-loop will only be executed if newArray is larger than oldArray.
One possible solution is to copy the oldArray, then iterate over newArray and check if the same value exists.
function mergeArrayWithLatestData (newData, oldData) {
let arr = oldData;
for(let i = 0; i < newData.length; i++) {
let exists = false;
for(let j = 0; j < oldData.length; j++) {
if(newData[i].name === oldData[j].name && newData[i].label === oldData[j].label) {
exists = true;
arr[j] = newData[i];
}
}
if(!exists) {
arr.push(newData[i]);
}
}
return arr;
}
var newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]
var oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]
console.log(mergeArrayWithLatestData(newArray, oldArray));
You make copies of the original arrays, and in the first one, or change the element, or add:
function mergeArrayWithLatestData (a1, a2) {
var out = JSON.parse(JSON.stringify(a1))
var a2copy = JSON.parse(JSON.stringify(a2))
a2copy.forEach(function(ae) {
var i = out.findIndex(function(e) {
return ae.name === e.name && ae.label === e.label
})
if (i!== -1) {
out[i] = ae
} else {
out.push(ae)
}
})
return out
}
[ https://jsfiddle.net/yps8uvf3/ ]
This is Using a classic filter() and comparing the name/label storing the different pairs using just +. Using destructuring assignment we merge the two arrays keeping the newest first, so when we check the different the newest is always the remaining.
var newArray = [{ name: "abc", label: "abclabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4] }];
var oldArray = [{ name: "oldArray", label: "oldArrayLabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4, 5] }];
var diff = [];
oldArray = [...newArray, ...oldArray].filter(e => {
if (diff.indexOf(e.name + e.label) == -1) {
diff.push(e.name + e.label);
return true;
} else {
return false; //<--already exist in new Array (the newest)
}
});
console.log(oldArray);
Create an object, with key as name and label. Now, first add all the oldData records to the object and then add newData records in object. If there are any objects in common with same name and label, it will overwrite the old Data value. Finally, get the values of the Object which is the merged data set.
var arr1 = [{name: 'def', label: 'abclabel', values: [6,7]}, {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}];
var arr2 = [{name: 'xy', label: 'abclabel', values: [6,7]}, {name: 'abc', label: 'abclabel', values: [6,7]}];
function mergeArrayWithLatestData(newData, oldData) {
var result = {};
[...oldData, ...newData].forEach(o => result[o.name + "~~$$^^" + o.label] = o);
return Object.values(result);
}
let result = mergeArrayWithLatestData(arr1, arr2);
console.log(result);
Alternative: using a Map as the initial value in a reducer. You should know that (as in the selected answer) you loose information here, because you're not comparing on the values property within the array elements. So one of the objects with name/label pair test/testlabel will be lost in the merged Array. If concatenation in the snippet was the other way around (so newArray.concat(oldArray), the test/testLabel Object within the merged Array would contain another values property value.
const newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
];
const oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
];
const merged = [
...oldArray.concat(newArray)
.reduce( (map, value) =>
map.set(`${value.name}${value.label}`, value),
new Map())
.values()
];
console.log(merged);
function mergeArray(newArray, oldArray) {
var tempArray = newArray;
oldArray.forEach(oldData => {
var isExist = tempArray.findIndex(function (newData) {
return oldData.name === newData.name;
});
if (isExist == -1) {
tempArray.push(oldData);
}
});
return tempArray;
}
var newArray = [{
name: 'abc',
label: 'abclabel',
values: [1, 2, 3, 4, 5]
}, {
name: 'test',
label: 'testlabel',
values: [1, 2, 3, 4]
}];
var oldArray = [{
name: 'oldArray',
label: 'oldArrayLabel',
values: [1, 2, 3, 4, 5]
}, {
name: 'test',
label: 'testlabel',
values: [1, 2, 3, 4, 5]
}];
var resultArray = [];
resultArray = mergeArray(newArray, oldArray);
console.log(resultArray);

How to change id to value in object

Have an object that I received from server. in that look
I need to change all "id" to name "value"
Try to parse to JSON change it and convert to the array, but have very bad results
var x = nextProps.campus;
var fff = JSON.stringify(x);
var res = fff.replace(/name/g, "value");
var arr = [];
for (var prop in res) {
arr.push(res[prop]);
}
in result I need like this
var options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
You can use Array#map()
var body = [{
id: 1,
name: "school_test_1"
}, {
id: 2,
name: "school_test_2"
}];
var options = body.map((x) => ({value:x.id,label:x.name}));
console.log(options);
You could iterate the array ach assign the new property with the old value and delete the proerty then.
var options = [{ name: 'one', label: 'One' }, { name: 'two', label: 'Two' }];
options.forEach(function (o) {
o.value = o.name;
delete o.name;
});
console.log(options);
You can do that with lodash something like this:
var myData= [{
id: 1,
name: "school_test_1"
}, {
id: 2,
name: "school_test_2"
}]
var changeLabel= {
id: 'value',
name: 'label'
};
var newArray = _.map(myData ,function(obj) {
return _.mapKeys(obj, function(value, key) {
return changeLabel[key];
});
});

How can I return the property values of a nested JavaScript array nested in an object from JSON?

Given a JS array containing many objects which all contain arrays:
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
How do I efficiently extract the inner most array (pages) values into an array?
var dataArray = [
{url: "www.abc.com", title: "abc"},
{url: "www.123.com", title: "123"},
{url: "www.xyz.com", title: "xyz"}
]
The easiest way to do this is to use Array#map like so:
var dataArray = data.map(function(o){return o.pages});
If pages is an array of objects (not a single object), this will result in an array of arrays, which you will need to flatten out for example using Array#reduce:
dataArray = dataArray.reduce(function(a,b){return a.concat(b)}, []);
You are looking for a flatMap
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
const concat = (xs, ys) => xs.concat(ys);
const prop = x => y => y[x];
const flatMap = (f, xs) => xs.map(f).reduce(concat, []);
console.log(
flatMap(prop('pages'), data)
);
If by "efficiently" you actually mean "concisely", then
[].concat(...data.map(elt => elt.pages))
The data.map will result in an array of pages arrays. The [].concat(... then passes all the pages arrays as parameters to concat, which will combine all of their elements into a single array.
If you are programming in ES5, the equivalent would be
Array.prototype.concat.apply([], data.map(function(elt) { return elt.pages; }))
Here's a working example on how to achieve what you want:
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}, {url:"www.google.com", title: "Google"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
var arr = Array();
var arr2 = Array();
// You can either iterate it like this:
for (var i = 0; i < data.length; i++) {
// If you only want the first page in your result, do:
// arr.push(data[i].pages[0]);
// If you want all pages in your result, you can iterate the pages too:
for (var a = 0; a < data[i].pages.length; a++) {
arr.push(data[i].pages[a]);
}
}
// Or use the array map method as suggested dtkaias
// (careful: will only work on arrays, not objects!)
//arr2 = data.map(function (o) { return o.pages[0]; });
// Or, for all pages in the array:
arr2 = [].concat(...data.map(function (o) { return o.pages; }));
console.log(arr);
console.log(arr2);
// Returns 2x [Object { url="www.abc.com", title="abc"}, Object { url="www.123.com", title="123"}, Object { url="www.xyz.com", title="xyz"}]
use array map() & reduce() method :
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
var dataArray = data.map(function(item) {
return item.pages;
});
dataArray = dataArray.reduce(function(a,b) {
return a.concat(b);
}, []);
console.log(dataArray);

Categories