Loop at JSON array and create a single JSON string - javascript

This should be easy but for some reason I'm stuck -
if I have a json like this and need to convert it:
{ data : [
{id : data1, name : "Description"},
{id : data2, name : "Contribution"},
{id : data3, name : "Footer"},
]}
into something like this?
{
data : [
{ data1: "Description" , data2: "Contribution", data3: "Footer" },
]}
Thanks,
Stuart

A small Array.prototype.reduce should do the job:
var obj = {
data: [
{ id: 'data1', name: 'Description' },
{ id: 'data2', name: 'Contribution' },
{ id: 'data3', name: 'Footer' },
]
};
obj.data = obj.data.reduce(function (r, a) {
r[a.id] = a.name;
return r;
}, {});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

You can use a for loop over the array.
var newData = [];
for(var i=0;i<data['data'].length;i++){
var obj={};
obj[data['data'][i]['id']]=data['data'][i]['name'];
newData.push(obj);
}
console.log(newData);
Refer fiddle
Updated Answer
var newArray = data['data'].map(function(obj){
var rObj = {};
rObj[obj.id] = obj.name;
return rObj;
});
You can use Array.map method for that also.
Refer fiddle-map

You can try to use the underscore.js lib.
Then check this example for your desired result Group By
Enjoy ;-)

var array=[];
for(int i=0; i<data.length; i++){
var object={};
object[data[i].id=data[i].name];
array.push(obj);
}

You can do it almost in a single line using lodash:
var obj1 = { data : [
{id: "data1", name: "Description"},
{id: "data2", name: "Contribution"},
{id: "data3", name: "Footer"},
]};
var obj2 = {
data: _.zipObject(_.pluck(obj1.data, "id"),
_.pluck(obj1.data, "name"))
}
document.write(JSON.stringify(obj2, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Have a look at _.pluck and _.zipObject.
You can also use underscore but lodash is faster, more complete, and you can create custom build with only what you need.

Related

How to add label to js array?

Hi I am looking to create an array that looks similar to this
const userList = {
123: "Tom",
124: "Michael",
125: "Christin",
};
it contains both value and label, what I tried so far
let raw = []
for (let x in data) {
raw.push(data[x].facility_name : data[x].id)
}
but it didn't work because "," was expected, if someone can help please
You are confusing arrays and objects. You need to add a key to an object not push. I kept it as a for in loop, but a for of loop would make more sense.
const data = [
{ id: 1, facility_name: "foo1" },
{ id: 2, facility_name: "foo2" },
{ id: 3, facility_name: "foo3" }
];
let raw = {};
for (let x in data) {
raw[data[x].id] = data[x].facility_name;
}
console.log(raw);
How I would code it using reduce.
var data = [
{ id: 1, facility_name: "foo1" },
{ id: 2, facility_name: "foo2" },
{ id: 3, facility_name: "foo3" }
];
const raw = data.reduce(function (acc, facility) {
acc[facility.id] = facility.facility_name;
return acc;
}, {})
console.log(raw);
IF your data has nested objects then you might do this:
let raw = {};
for(x in data)
{
raw[data[x].facility_name] = data[x].id;
}
This is useful when you want to get rid of duplicates.

Modification of array objects

I am trying to rebuild an array ,so I need suggestion on doing it using best practices.
I have an array object as follows:
MainObject:
0:"Namebar"
1: Object
Name: "Title1"
Url: "Url1"
2: Object
Name: "Title2"
Url: "Url2"
3: Object
Name: "Title3"
Url: "Url1"
In the above since the "url" is same , I want to group it same object and I am expecting the output in the following format:
0: "Url1"
1: Object
Name : "Title1"
Url: "Namebar"
2: Object
Name : "Title3"
Url: "Namebar"
1: "Url2"
1: Object
Name : "Title2"
Url: "Namebar"
I am trying to have two arrays and loop through the MainObject for swapping the items which I know is not only a teadious process but very much high on time complexity.
For example like :
var extract1 = MainObject[0];
var extract2 = using for loop to extract and swap ......
I am not getting any other way of achieving this. Any approach for this in javascript/jquery?
This should do the job:
var extract1 = MainObject[0];
var newArray = {};
var newArrProp;
var extract1Props = Object.keys(extract1);
for( i = 0; i< extract1Props.length; i++)
{
newArrProp = extract1Props[i];
var nestedObjects = extract1[newArrProp];
for(j = 0; j < nestedObjects.length; j++)
{
if(!newArray[nestedObjects[j].Url])
{
newArray[nestedObjects[j].Url] = [];
}
newArray[nestedObjects[j].Url].push({Name:nestedObjects[j].Name,Url:newArrProp});
}
}
Working fiddle
You could use some loops.
var MainObject = [{ "Namebar": [{ Name: "Title1", Url: "Url1" }, { Name: "Title2", Url: "Url2" }, { Name: "Title3", Url: "Url1" }] }],
object2 = [];
MainObject.forEach(function (a) {
Object.keys(a).forEach(function (k) {
a[k].forEach(function (b) {
var temp = {};
if (!this[b.Url]) {
temp[b.Url] = [];
this[b.Url] = temp[b.Url];
object2.push(temp);
}
this[b.Url].push({ name: b.Name, Url: k });
}, this);
}, this);
}, Object.create(null));
document.write('<pre>object2 ' + JSON.stringify(object2, 0, 4) + '</pre>');
document.write('<pre>MainObject ' + JSON.stringify(MainObject, 0, 4) + '</pre>');

javascript: truncate object properties in an array

I have an array of objects, say the object looks like following:
var row = {
data: 'test',
text: 'test'
};
I want to loop through the array and just get the object with text property.
What is the best way to do it?
So, I want to loop and the object should look like: row = {text: 'test'}
I tried something like below without luck:
arr.forEach(function (item){ //arr is the array of object
return {text: item.text};
});
Use Array.prototype.map for that:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
return {text: item.data};
});
The result will look like:
[{ text: 'testData' }]
If you want it to be [ {testText: 'testData' }] then:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
var obj = {};
obj[item.text] = item.data;
return obj;
});
As you want a object with single key value pair, you don't need to store in object form. You can save them as an array.
var array = [
{
text : "text",
data : "data"
},
{
text : "text1",
data : "data1"
}
]
var newArray = array.map(function(item){
return item.data;
});
your output will look like
['text','text1']

How to push var:var to array

I have the following code:
var fieldArr = [];
dimensions.forEach(function (dimension) {
fieldArr.push({dimension.id:dimension.name});
});
This generates an error.
What I'm trying to do is given this dimensions
{
id: abc
name: ddd
},
{
id: aaa
name:kkk
}
I want the fieldsArr to look like this
[abc] -> ddd
[aaa] -> kkk
You need to populate an object rather than an array.
Javascript
var dimensions = [{
id: "abc",
name: "ddd"
}, {
id: "aaa",
name: "kkk"
}],
fieldArr = {};
dimensions.forEach(function (dimension) {
fieldArr[dimension.id] = dimension.name;
});
console.log(fieldArr);
Output
Object {abc: "ddd", aaa: "kkk"}
jsfiddle
Then fieldArr shouldn't be an array, but an object.
var fieldArr = {};
dimensions.forEach(function (dimension) {
fieldArr[dimension.id] = dimension.name;
});
simply
fieldArr[dimension.id] = dimension.name

Joins in Javascript

I have 2 lists of objects:
people =
[{id: 1, name: "Tom", carid: 1},
{id: 2, name: "Bob", carid: 1},
{id: 3, name: "Sir Benjamin Rogan-Josh IV", carid: 2}];
cars=
[{id: 1, name: "Ford Fiesta", color: "blue"},
{id: 2, name: "Ferrari", color: "red"},
{id: 3, name: "Rover 25", color: "Sunset Melting Yellow with hints of yellow"}];
Is there a function (possibly in Angular, JQuery, Underscore, LoDash, or other external library) to do a left join in one line on these? Something like:
peoplewithcars = leftjoin( people, cars, "carid", "id");
I can write my own, but if LoDash has an optimised version I'd like to use that.
This implementation uses the ES6 spread operator. Again, not a library function as asked for.
const leftJoin = (objArr1, objArr2, key1, key2) => objArr1.map(
anObj1 => ({
...objArr2.find(
anObj2 => anObj1[key1] === anObj2[key2]
),
...anObj1
})
);
You can use Alasql JavaScript SQL library to join two or more arrays of objects:
var res = alasql('SELECT people.name AS person_name, cars.name, cars.color \
FROM ? people LEFT JOIN ? cars ON people.carid = cars.id',[people, cars]);
Try this example at jsFiddle.
Linq.js http://linqjs.codeplex.com/ will do joins along with many other things
It is not hard to implement using underscore.js
function leftJoin(left, right, left_id, right_id) {
var result = [];
_.each(left, function (litem) {
var f = _.filter(right, function (ritem) {
return ritem[right_id] == litem[left_id];
});
if (f.length == 0) {
f = [{}];
}
_.each(f, function (i) {
var newObj = {};
_.each(litem, function (v, k) {
newObj[k + "1"] = v;
});
_.each(i, function (v, k) {
newObj[k + "2"] = v;
});
result.push(newObj);
});
});
return result;
}
leftJoin(people, cars, "carid", "id");
You can do such stuff in plain javascript.
people.map(man =>
cars.some(car => car.id === man.carid) ?
cars.filter(car => car.id === man.carid).map(car => ({car, man})) :
{man}
).reduce((a,b)=> a.concat(b),[]);
No, LoDash does not have join it's prety easy to implement your own though, this isn't quite a join but selects all people with a matching car:
var peopleWithCars = _.filter(people, function (person) {
return _.exists(cars, function(car) {
return car.id === person.id;
});
});
This example uses Lodash to left join the first matched object. Not quite what the question asks, but I found a similar answer helpful.
var leftTable = [{
leftId: 4,
name: 'Will'
}, {
leftId: 3,
name: 'Michael'
}, {
leftId: 8,
name: 'Susan'
}, {
leftId: 2,
name: 'Bob'
}];
var rightTable = [{
rightId: 1,
color: 'Blue'
}, {
rightId: 8,
color: 'Red'
}, {
rightId: 2,
color: 'Orange'
}, {
rightId: 7,
color: 'Red'
}];
console.clear();
function leftJoinSingle(leftTable, rightTable, leftId, rightId) {
var joinResults = [];
_.forEach(leftTable, function(left) {
var findBy = {};
findBy[rightId] = left[leftId];
var right = _.find(rightTable, findBy),
result = _.merge(left, right);
joinResults.push(result);
})
return joinResults;
}
var joinedArray = leftJoinSingle(leftTable, rightTable, 'leftId', 'rightId');
console.log(JSON.stringify(joinedArray, null, '\t'));
Results
[
{
"leftId": 4,
"name": "Will"
},
{
"leftId": 3,
"name": "Michael"
},
{
"leftId": 8,
"name": "Susan",
"rightId": 8,
"color": "Red"
},
{
"leftId": 2,
"name": "Bob",
"rightId": 2,
"color": "Orange"
}
]
Here's a simple loop I did for a Javascript (JQuery in this case) to "join" obj1 and obj2 on someID and add one property from obj2 to obj1.
If you want to do a more complete join, you can go through and expand it to loop on obj2.hasOwnProperty() and copy that over as well.
$.each(obj1,function(i){
$.each(obj2, function(k){
if (obj2[k].someID == obj1[i].someID ){
obj1[i].someValue = obj2[k].someValue;
}
});
});

Categories

Resources