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
Related
I am having an object like this
$scope.object1 = { [{"customer_gid": 807,
"customer_name": "APPLIANCES"}]}
so my data should be like this
$scope.object2 = { [{"customer_gid": 807,
"customer_name": "APPLIANCES", type:[{"scheduletype_gid": 1, "scheduletype_code": "SCT001", "scheduletype_name": "BOOKING"}]}, }{"customer_gid": 798, "customer_name": "
AGENCIES PVT LTD"}, ]}]
how to append this two object using angularjs
You can use Object.assign()
var target = {a: 1};
var source1 = {b: 2};
var newObj = Object.assign(target, source1);
console.log(newObj);
you can't put array directly in the object as : { [] }
for doing that we should put array with param as: { myArray: [] }
for appending another param to our object you can do this:
var object = { myArray: [{ somthing: 'test' }] }
object['another'] = { name: 'hello world' }
//result
//object = { myArray: [{ somthing: 'test' }], another: { myArray: [{ somthing: 'test' }] } }
I've a Javascript array of strings like:
var array = [{
string: 'path1/path2/path3'
}, {
string: 'path1/path4/path5'
}, {
string: 'path1/path2/path6'
}, {
string: 'path10/path7'
}, {
string: 'path10/path8/path9'
}];
and I need to create a data model structured like this:
-- path1
-- path2
-- path3
-- path6
-- path4
-- path5
-- path10
-- path7
-- path8
-- path9
How can I achive this? Do you have any advice? Thank you
Edit:
I was thinking something like:
var paths = {
children = [
{
name: "path1"
children: [
{
name: "path2",
children: [
{
name: "path3",
children: []
}]
},
{
name: "path4",
children: [
{
name: "path5",
children: []
}]
}
}
],
.......
};
This should get you started:
var array = [{
string: 'path1/path2/path3'
}, {
string: 'path1/path4/path5'
}, {
string: 'path1/path2/path6'
}, {
string: 'path10/path7'
}, {
string: 'path10/path8/path9'
}];
let tree = {};
for (let {string} of array) {
let t = tree;
for (let c of string.split('/'))
t = t[c] || (t[c] = {});
}
console.log(tree);
I have an api call that replies with an updated jSON object, I also have 1 static jSON object file. I am trying to compare a value in the object per teams with the same name.
So if Team John had 22 in the old file, and has 28 now, the new object should output Team John as 6. Subtracting the 2 and displaying the difference.
I have made a jsFiddle to help understand and update.
LATEST UPDATE: The answer has been solved by mscdeveloper! Check for his post and answer below.
UPDATE (not the answer): I have found a solution while searching in stackoverflow, this does EXACTLY what I want, but I lost the team's name in the process, how can I fix the code to where it doesn't delete it, I know it has something to do with the groupByTypeID function I have?
Updated jsFiddle: https://jsfiddle.net/kqmfsz9n/5/
var obj1 = {
"teams": [
{
name: 'Test 1',
numMembers: '50'
},
{
name: 'Test 2',
numMembers: '12'
}
]
};
var obj2 = {
"teams": [
{
name: 'Test 1',
numMembers: '75'
},
{
name: 'Test 2',
numMembers: '18'
}
]
};
var newObj = {};
function groupByTypeID(arr) {
var groupBy = {};
jQuery.each(arr, function () {
groupBy[this.name] = parseInt(this.numMembers);
});
return groupBy;
}
var userArrayGroups = groupByTypeID(obj2.teams);
var origArrayGroups = groupByTypeID(obj1.teams);
var newObj = [];
for (var prop in userArrayGroups) {
newObj[prop] = userArrayGroups[prop] - origArrayGroups[prop];
newObj.push(userArrayGroups[prop] - origArrayGroups[prop]);
if (newObj[prop] == 0) {
delete newObj[prop];
}
}
console.log(newObj);
All help is appreciated!
Thank you.
var obj1 = {
"teams": [
{
name: 'Test 1',
numMembers: '50'
},
{
name: 'Test 2',
numMembers: '12'
}
]
};
var obj2 = {
"teams": [
{
name: 'Test 1',
numMembers: '75'
},
{
name: 'Test 2',
numMembers: '18'
}
]
};
var newObj = {};
var items_arr=[]; //array of obj2 not exist in obj1
if(obj1.teams){ //if exist array of teams obj1
var o1teams = obj1.teams;
if(obj2.teams){ //if exist array of teams obj2
var o2teams = obj2.teams;
for(var key2 in o2teams){
var o2teams = obj2.teams;
for(var key1 in o1teams){
if(o2teams[key2].name==o1teams[key1].name){
var numMembers_o1_int=parseInt(o1teams[key1].numMembers)||0;
var numMembers_o2_int=parseInt(o2teams[key2].numMembers)||0;
var result_numMembers_int=numMembers_o2_int-numMembers_o1_int;
var result_numMembers=result_numMembers_int+''; //convert to string
var items_for_add=o1teams[key1];
items_for_add.numMembers=result_numMembers;
items_arr.push(items_for_add);
}
}
}
}
}
newObj.items=items_arr;
console.log(newObj);
https://jsfiddle.net/mscdeveloper/uxv1t2a7/3/
I've been searching and searching and haven't found a solution...even though, likely, it's simple. How do I create something that will give me this:
myArray['key1'].FirstName = "First1";
myArray['key1'].LastName = "Last1";
myArray['key2'].FirstName = "First2";
myArray['key2'].LastName = "Last2";
myArray['key3'].FirstName = "First3";
myArray['key3'].LastName = "Last3";
And then say something like, alert(myArray['key2'].FirstName);
And will I be able to iterate through it like:
for(i=0; i < myArray.length; i++){
//do whatever
}
Thanks in advance!
You can init an object something like that:
{
"key1": {FirstName: "first1", LastName: "last1"}
"key2": {FirstName: "first2", LastName: "last2"}
"key3": {FirstName: "first3", LastName: "last3"}
}
Sample function for init your array:
function initArray(){
for(var i=1; i< count+1; i++) {
var newElement = {}
newElement.FirstName = "first" + i;
newElement.LastName = "last" + i;
var keyName = "key" + i
var obj = {};
myArray[keyName] = newElement
}
}
Now "myArray["key2"] is accessible.
http://jsfiddle.net/jq5Cf/18/
You can't do what you're trying to do in javascript! (because javascript can't do associative arrays)
I would go for an object which has an internal array to store other things
var container = {};
container.things = [];
container.things.push({FirstName: 'First1', LastName: 'Last1'});
now you can do..
for(var i in container.things) {
alert(container.things[i].FirstName);
}
In JavaScript we use arrays like this, [] for Arrays and Objects are in {}
var MyArray = [
{FirstName: "Firsname1" , LastName: "Lasname1"},
{FirstName: "Firsname2" , LastName: "Lasname2"}
]
Your myarray variable construction is in notation of objects of objects.
var myArray = {'key1':
{
'FirstName' : "First1",
'LastName' : "Last1"
}};
In order to access the values should be like array of objects.
var myArray = [
{
'FirstName' : "First1",
'LastName' : "Last1"
},
];
or notation can be like below:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
I have a series of JSON entries:
[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]
I am trying to convert this array of Objects as painlessly as possible into two objects - one with title name_A, and the second with the title name_B. Objects have to contain the title and an array of matching num-name pairs:
[{title: "name_A", names:[{"1", "Alex}, {"2", "Anne"}]}, {title:"name_B", names: [{"1", "Bob"}, {"2", "Barbra"}]}]
At first I tried simply to create two objects by reducing the array of object twice, once for name_A and second time for name_B and later glue everything together:
// get 'names' array
var name_A = objArray.reduce(function(memo, curr) {
memo.push({curr.num, curr.name_A})
return memo;
}, []);
But even this is failing. Why there is no push method for memo if I initialize reduce with an empty array?
And second question, am I on a right track or is there a better way to achieve this?
Comments inline, made a few minor corrections to the expectations.
var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]
var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;
// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);
return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);
// pretty print our output
console.log(JSON.stringify(output, null, " "))
var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]
var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;
// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);
return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);
so.log(output)
<pre id="output"></pre>
<script>
var so = {
log: function(o) {
document.getElementById("output").innerHTML = JSON.stringify(o, null, " ")
}
}
</script>
The problem with your code is that { curr.num, curr.name_A } is not a valid object, it's missing the property names. I've added properties num and name in my code below.
var name_A = [];
var name_B = [];
objArray.forEach(function(curr) {
name_A.push({num: curr.num, name: curr.name_a});
name_B.push({num: curr.num, name: curr.name_B});
});
var result = [
{ title: "name_A" }, names: name_A },
( title: "name_B" }, names: name_B }
];
Also, if you want to make an array out of the results of looping over an array, you should use .map rather than .reduce.
Assuming only property num is fixed. All other properties are treated as data, like name_A or name_B.
var a = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }],
result = [];
a.forEach(function (el) {
var num = el.num;
Object.keys(el).forEach(function (k) {
function tryFindIndexAndSetNames(aa, i) {
if (aa.title === k) {
result[i].names[num] = el[k];
return true;
}
}
if (k !== 'num' && !result.some(tryFindIndexAndSetNames)) {
var o = {};
o[num] = el[k];
result.push({ title: k, names: o });
}
});
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');