How to change id to value in object - javascript

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];
});
});

Related

Javascript - How to combine all combinations into an array of objects

I have the following array:
[{
name: 'foo',
values: '10,12'
},
{
name: 'bar',
values: 'red,blue'
}]
Using some javascript logic I would like to output the following array:
[{
option1: 10,
option2: 'red'
},
{
option1: 10,
option2: 'blue'
},
{
option1: 12,
option2: 'red'
},
{
option1: 12,
option2: 'blue'
}]
What is the best and correct way to achieve this using javascript?
Lets say your first array is named arr.
var arr = [{
name: 'foo',
values: '10,12'
},
{
name: 'bar',
values: 'red,blue'
}];
var v1 = arr[0].values.split(',');
var v2 = arr[1].values.split(',');
var res = new Array();
for(i in v1){
for(j in v2){
res.push({'option1':v1[i],'option2':v2[j]});
}
}
console.log(res);
Here's an approach that can handle an arbitrary number of objects.
function valuesCrossProduct(input) {
return input.flatMap((current, index, array) => {
let result = [];
let values = current.values.split(',');
for (let v of values) {
for (let i = 0; i < array.length; i++) {
if (i <= index) {
// Skip creating cross products with self (i.e. == index)
// and with previously visited objects (i.e. < index).
continue;
}
let iValues = array[i].values.split(',');
let currentKey = `option${index}`;
let iKey = `option${i}`;
for (let iv of iValues) {
result.push({
[currentKey]: v,
[iKey]: iv,
});
}
}
}
return result;
});
}
let twoElementArray = [{
name: 'foo',
values: '10,12'
},
{
name: 'bar',
values: 'red,blue',
}];
let threeElementArray = [{
name: 'foo',
values: '10,12'
},
{
name: 'bar',
values: 'red,blue',
},
{
name: 'baz',
values: 'wham,bam',
}];
console.log(valuesCrossProduct(twoElementArray));
console.log(valuesCrossProduct(threeElementArray));
Functional for the win.
Note: as it is, this only works for an array of two objects, with any number of values in each, where the first set of values are numbers and the second set are strings, which is what you described above.
const arr = [{
name: 'foo',
values: '10,12'
},
{
name: 'bar',
values: 'red,blue'
}];
const values = arr
.map(o => o.values.split(','))
.reduce((cur, next) => {
return cur.map(c => {
return next.map(n => {
return {
option1: parseInt(c),
option2: n
};
});
}).flat();
});
console.log(values);
If you need generic approach to get possible options from various values.
const options = data => {
let sets = [[]];
data.forEach(({ values }, i) => {
const new_set = [];
values.split(",").forEach(value => {
new_set.push(
Array.from(sets, set => [...set, [`option${i + 1}`, value]])
);
});
sets = new_set.flatMap(set => set);
});
return sets.map(set => Object.fromEntries(set));
};
const data = [
{
name: "foo",
values: "10,12"
},
{
name: "bar",
values: "red,blue,green"
},
{
name: "test",
values: "top,bottom"
}
];
console.log(options(data));

JavaScript: Convert array of objects into hashmap

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);

Immutable.js algorithm: List.update_or_add(item)

I want to concatenate 2 lists in immutable.js.
Both lists have this structure: { id, value }
The algorithm concatenate should do this:
If an ID exists in both list1 and list2 take the value from list2.
let list1 = [
{ id: 1, value: 'foo' },
{ id: 3, value: 'bar' },
{ id: 2, value: 'baz' },
]
let list2 = [
{ id: 1, value: 'quux' }, // id 1 exists in list1
{ id: 4, value: 'asd' },
]
let result = [
{ id: 1, value: 'quux' }, // from list 2
{ id: 3, value: 'bar' },
{ id: 2, value: 'baz' },
{ id: 4, value: 'asd' },
]
If Immutable.js has this functionality with another type (eg. Dictionary), I could also use that.
Algorithms for union
First you have to maintain two map with key as id and value as object then check for length of array which is of bigger size and pass the bigger size array with small size map to merged function there you can iterate over the array and check if it's exists in the map if yes then update the object and delete that row from map otherwise add the object into output. After the for loop complete check if map has element present then push all the values from map into output array and return;
index.js
const old = [
{ id: 1, value: 'foo' },
{ id: 3, value: 'bar' },
{ id: 2, value: 'baz' },
];
const newa = [
{ id: 1, value: 'quux' }, // update
{ id: 4, value: 'asd' }, // push
];
function merged(input,filterMap){
var output = [];
input.forEach(function(eachRow){
if(filterMap.hasOwnProperty(eachRow.id)){
output.push(Object.assign(eachRow,filterMap[eachRow.id]));
delete filterMap[eachRow.id];
}else{
output.push(eachRow);
}
});
if(Object.keys(filterMap).length > 0){
output = output.concat(Object.values(filterMap));
}
return output;
}
function parseData(first,second){
var mapFirst = {},
mapSecond = {};
var output = [];
first.forEach(function(eachRow){
mapFirst[eachRow.id] = eachRow;
});
second.forEach(function(eachRow){
mapSecond[eachRow.id] = eachRow;
});
if(first.length > second.length){
return merged(first,mapSecond);
}else{
return merged(second,mapFirst);
}
}
console.log(parseData(old,newa));
Working jsFiddle demo - https://jsfiddle.net/qz25hnmf/

The operation of the JavaScript array and object

oldList:
var oldList = [
{id:1, time:'2018-02-06 09:00-10:00', title:'aa'},
{id:2, time:'2018-02-06 11:00-12:00', title:'bb'},
{id:3, time:'2018-02-07 10:00:02', title:'cc'},
{id:4, time:'2018-02-07 09:00-10:00', title:'dd'}
];
console.log(oldList);
Desired:
var newList = [
{
'2018-02-06' : [
{id:1, time:'2018-02-06 09:00-10:00', title:'aa'},
{id:2, time:'2018-02-06 11:00-12:00', title:'bb'},
]
},
{
'2018-02-07' : [
{id:4, time:'2018-02-07 09:00-10:00', title:'dd'},
{id:3, time:'2018-02-07 10:00:02', title:'cc'},
]
},
];
console.log(newList);
How can I get the following result from this array and object?
I haven't found a good solution at the moment。
You can use reduce for this.
var oldList = [{
id: 1,
time: '2018-02-06 09:00-10:00',
title: 'aa'
},
{
id: 2,
time: '2018-02-06 11:00-12:00',
title: 'bb'
},
{
id: 3,
time: '2018-02-07 10:00:02',
title: 'cc'
},
{
id: 4,
time: '2018-02-07 09:00-10:00',
title: 'dd'
}
];
var newList = oldList.reduce(function(c, i) {
let t = i.time.split(" ")[0];
c[t] = c[t] || [];
c[t].push(i);
return c;
}, {});
console.log( newList );
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
you can use lodash to do this.
var newList = _.groupBy(oldList, function(o) {
return o.time.split(" ")[0];
});
var newList = {};
for (var i = 0; i < oldList.length; i++) {
var item = oldList[i];
var key = item.time; //here you can transform the key as you like (ie remove time)
if (newList[key] == null) {
newList[key] = [];
}
newList[key].push(item );
}
I created a dictionary. For each item in your old list I check if in the new list exist a key with your timestamp. If not, create a new entry with an empty array. Then, in both case, push your item into the specific array
Here's a solution without using reduce.
var oldList = [{
id: 1,
time: '2018-02-06 09:00-10:00',
title: 'aa'
}, {
id: 2,
time: '2018-02-06 11:00-12:00',
title: 'bb'
}, {
id: 3,
time: '2018-02-07 10:00:02',
title: 'cc'
}, {
id: 4,
time: '2018-02-07 09:00-10:00',
title: 'dd'
}];
var uniqueDates = []
for (i in oldList) {
if (uniqueDates.indexOf(oldList[i]['time'].split(' ')[0]) == -1) {
uniqueDates.push(oldList[i]['time'].split(' ')[0])
}
}
var newList = []
for (i in uniqueDates) {
var val = {}
val[uniqueDates[i]] = []
for (j in oldList) {
if(oldList[j]['time'].split(' ')[0] == uniqueDates[i]){
val[uniqueDates[i]].push(oldList[j])
}
}
newList.push(val)
}
console.log(newList)
But I like #Eddie's answer better

How to convert an array to an object in Lodash?

I have:
{
dis:{["String1","String2","String3"]},
par:"pony"
}
And I want to turn it into this:
[
{ name: 'String1', value: "pony" },
{ name: 'String2', value: "pony" },
{ name: 'String3', value: "pony" }
]
If you change to valid js data you can do this with reduce()
var obj = {
dis: ["String1", "String2", "String3"],
par: "pony"
}
var result = obj.dis.reduce(function(r, e) {
r.push({name: e, value: obj.par});
return r;
}, []);
console.log(result)
You can do it easily, but beware you have double parentheses (mustaches and square bracket).
var
data = {
dis: ["String1","String2","String3"],
par: "pony"
},
result = [];
for (var index in data.dis)
result.push({ name: data.dis[index], value: data.par}
you can find the fiddle here.
You can do it using Array.protoype.map:
var obj = {
dis:["String1","String2","String3"],
par:"pony"
};
var arrOfObj = obj.dis.map(function(name) {
return {
name: name,
value: obj.par
}
});
console.log(arrOfObj)
Or lodash's _.map:
var obj = {
dis:["String1","String2","String3"],
par:"pony"
};
var arrOfObj = _.map(obj.dis, function(name) {
return {
name: name,
value: obj.par
}
});
console.log(arrOfObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

Categories