I have sample JSON in form of
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var result = [];
sample.forEach(function(e){
let obj = {}
obj.id=e.id
obj['somekey']=e.children[0].value
obj['someanotherkey']=e.children[1].type
result.push(obj);
})
console.log(result)
How do i can achieve same using map es-6
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var output = sample.map(({ id, children }) => ({ id, ...children[0] }));
console.log(output);
.map() returns an array, so you must set up a variable to hold that result. Then, within the loop, you use return to effectively push items into the array.
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}];
let result = sample.map(function(e){
let obj = {}
obj.id=e.id;
obj['value']=e.children[0].value;
obj['type']=e.children[0].type
return obj;
});
console.log(result);
If you want to be able to chose the children index:
const getDataChild = (a, i) => a.map(({id, children:ch}) => ({id, ...ch[i]}));
console.log(getDataChild(sample, 0)); // where 0 is the desired index
Related
Hi I have an array of objects like below:
let tbrows = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}]
I want to get the maximum value of speciecnt for each row (i.e. after filtering the array) I would like it to be
let tbrows = [{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":3}];
I am using the following code that I found on the web to filter an array but it only filters on one attribute of object.
const max2 = tbrows.reduce((op, item) => op = op > item.speciescnt? op : item.speciescnt, 0);
You can also using reduce() to do it
let tbrows = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}]
let result = tbrows.reduce((a,c) => {
let obj = a.find(i => i.rowindx == c.rowindx)
if(!obj){
a.push(c)
}else if(c.speciescnt > obj.speciescnt){
obj.speciescnt = c.speciescnt
}
return a
},[])
console.log(result)
Turn the array into an object (right now, you're trying to turn it into just a number). Have the object be indexed by the row index, with the associated value for that row as the highest speciecnt found so far. Then you can turn the object back into an array.
const input = [{"rowindx":0,"speciescnt":2},{"rowindx":0,"speciescnt":3},{"rowindx":1,"speciescnt":2},{"rowindx":1,"speciescnt":3}];
const grouped = {};
for (const { rowindx, speciescnt } of input) {
grouped[rowindx] = Math.max(grouped[rowindx] ?? -Infinity, speciescnt);
}
const output = Object.entries(grouped)
.map(([rowindx, speciescnt]) => ({ rowindx, speciescnt }));
console.log(output);
Fairly new to JSON and I'm trying to get my head around conversions. I have an array:
['Role1', 'Role2', 'Role3']
and I'm trying to stringify it so that it reads as
{"Role1": true, "Role2": true, "Role3": true}
So far I've tried assigning the original array to an object and the calling stringify but I can't figure out how to add the boolean value in the string. Thanks in advance.
You'll have to create an intermediate reduce function to assign those values before converting to JSON.
const data = ['Role1', 'Role2', 'Role3']
const makeJson = () =>
JSON.stringify(data.reduce((a, c) => ({ ...a, [c]: true }), {}))
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Is this what you need as output?
const arr = ['Role1', 'Role2', 'Role3']
const result = JSON.stringify(arr.reduce((a, n)=>{
return {
...a,
[n]: new Boolean(true).toString()
}
},{}))
console.log(result)
Another approach could be to combine Object.fromEntries with Array.prototype.map
const data = ['Role1', 'Role2', 'Role3']
const result = Object.fromEntries(data.map(s => [s, true]));
console.log(JSON.stringify(result));
This should do the trick:
let rolesArray = ['Role1', 'Role2', 'Role3'];
let rolesObject = {};
// iterate over roles to fill an object
rolesArray.forEach((role) => {
rolesObject[role] = true;
});
JSON.stringify(rolesObject) // Outputs the desired string
Or in a more concise way but less readable for a SO example :
JSON.stringify(rolesArray.reduce((o, s) => { o[s] = true; return o }, {}));
I have a preference for using the for-loop — still valid but other methods will be much short.
var array = ["Role1", "Role2", "Role3"],
json = {};
for (i = 0; i < array.length; i++) {
json[array[i]] = true;
}
console.log(json);
Use reduce() so we can set the value to true without a second loop
Using the spread operator (...) to merge the objects
const data = ['Role1', 'Role2', 'Role3'];
const obj = data.reduce((prev, cur) => ({ ...prev, [cur]: true }), {});
console.log(obj);
console.log(JSON.stringify(obj));
{
"Role1": true,
"Role2": true,
"Role3": true
}
{"Role1":true,"Role2":true,"Role3":true}
if you want to do that you must use code Below .
json-encode(Array)
I have an object.
var x = {"id":"asc","metaid":"desc"}
I want to create another object which looks something like this.
[{id: {order:"asc"}},{metaid: {order:"desc"}}]
What I have already tried is this
const sc1 = [];
var def1 = {}
for (let key of Object.keys(obj)){
def1[key] = {order: obj[key]}
}
sc1.push(def1);
The above code doesn't give required output.
Need help with this.
Thanks
Map the entries of the object to return an object with a computed property name:
var x = {"id":"asc","metaid":"desc"};
const result = Object.entries(x)
.map(([prop, order]) => ({ [prop]: { order } }));
console.log(result);
You can use Array#from
var x = {"id":"asc","metaid":"desc"};
let out = Array.from(Object.entries(x), ([prop, value]) => ({[prop]: {order: value}}));
console.log(out)
In my JS project, I am using Lodash library to Extract property, split array, get unique values.
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
//Looping through the object to convert string to array
_.forEach(taskobj, function(value, key) {
taskobj[key].team = _.split(taskobj[key].team,',');
});
// using _.map to extract team and return array
// using _.flatten to flatten array
// using _.uniq to get unique values from flattned array.
return _.uniq(_.flatten(_.map(taskobj,'team')));
// logs - [1,2,3,4]
Is this the most efficient way to achieve this?
you can use reduce and start with a new Set() and add the values of team every time ( then convert it back to an array with the spread operator )
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
var result = [...taskobj.reduce((acc, {team}) => {
team.split(',').forEach(e => acc.add(e))
return acc
}, new Set())]
console.log(result)
This can be achieved by using lodash#flatMap with an iteratee that splits the team string into an array, which is then flattened by the mentioned function and then use lodash#uniq to get the final result.
var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Use simpler version
try this
var teams = [];
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
taskobj.map(obj => {
var teamSplit = obj.team.split(',');
teams = [...teams, ...teamSplit];
})
var uniqTeams = _.uniq(teams);
console.log('teams', teams);
console.log('uniqTeams', uniqTeams)
JsBin link
http://jsbin.com/bedawatira/edit?js,console
I have an Object as
var a ={
demo:[1,2,3],
demo1:[test1,test2,test3]
}`
I want to convert the above object into array of objects
var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}];`
can anyone help on this??
Iterate on the first array - demo, using Array#map function and then using the index of the first item access the demo1 appropriate item.
const a = {
demo: [1, 2, 3],
demo1: ['test1', 'test2', 'test3']
};
const mapped = a.demo.map((item, index) => ({ demo: item, demo1: a.demo1[index] }));
console.log(mapped);
You can use array#reduce to iterate through your array and using Object#keys() you can get the key of each object then iterate through each key and add to an accumulator object.
var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}],
result = a.reduce((r,o) => {
Object.keys(o).forEach(k => {
r[k] = r[k] || [];
r[k].push(o[k]);
});
return r;
},{});
console.log(result);