How to push the value in object in proper format - javascript

Following is my code to get the languages with Language id and language text
for (var p in $scope.bulk.Langugaes) {
$scope.lsLanguagewithTextndValue.push($scope.bulk.Langugaes[p].Value, $scope.bulk.Langugaes[p].Text);
}
but for above code the value in lsLanguagewithTextndValue
0:"1"
1:"Marathi"
2:"2"
3:"English"
4:"4"
5:"Hindi"
6:"3"
7:"French"
But I want output like this
1:Marathi
2:English
3.Hindi
4.French

$scope.lsLanguagewithTextndValue.push({ $scope.bulk.Langugaes[p].Value: $scope.bulk.Langugaes[p].Text });
Multiple arguments in .push just pushes each argument in to the array.

If you want to add a pair key - value do it like this:
obj[key] = value;
In your case it should be something like this:
for (var p in $scope.bulk.Langugaes) {
$scope.lsLanguagewithTextndValue[$scope.bulk.Langugaes[p].Value] = $scope.bulk.Langugaes[p].Text;
}

Try this.
const $scope = {
bulk: {
Languages: {
ln1: { value: 1, text: 'Marathi' },
ln2: { value: 2, text: 'English' },
ln3: { value: 3, text: 'Hindi' },
ln4: { value: 4, text: 'French' }
}
},
lsLanguagewithTextndValue: []
}
// just to make it more readable
const langs = $scope.bulk.Languages;
for (let p in langs) {
$scope.lsLanguagewithTextndValue.push({[langs[p].value]: langs[p].text})
}
console.log($scope.lsLanguagewithTextndValue);

In this case use map Array map. This function make a new array with elements of another.
$scope.lsLanguagewithTextndValue =
$scope.bulk.Langugaes.map((langugaes) => {
// langugaes its a element of $scope.bulk.Langugaes for example
// $scope.bulk.Langugaes[p]
return {langugaes.Value: langugaes.Text}
})
Result:
{
"1": "Marathi"
},
{
"2": "English"
},
{
"3": "Hindi"
},
{
"4": "French"
}

Related

Combine the result of two input fields with JavaScript?

I have as a result from an input form a couple of strings and I want them to convert them, so they fit as data for my ajax-request. I am looking for an easy way, but I can't get it right. Basically I want to convert/map this array:
[
{ name: "[1][apples]", value: "2" }
{ name: "[1][melons]", value: "1" }
{ name: "[2][apples]", value: "2" }
{ name: "[2][melons]", value: "4" }
{ name: "[3][apples]", value: "3" }
{ name: "[3][melons]", value: "2" }
]
into
[{"id": 1, "apples": 2, "melons": 1}, {"id": 2, "apples": 2, "melons": 4}, {...}]
Any idea? I would appreciate some hint? I could't not find an easy solution via html though.
Thanks
you can use a for loop to access each element and display them.
Refer to this link. For loop in multidimensional javascript array
Firstly, I have replaced the square brackets using a regular expression and formed a new array. After that, I have merged object having same ID using spread operator.
You can refer to the code below which solves this problem.
let array = [
{ name: "[1][apples]", value: "2" },
{ name: "[1][melons]", value: "1" },
{ name: "[2][apples]", value: "2" },
{ name: "[2][melons]", value: "4" },
{ name: "[3][apples]", value: "3" },
{ name: "[3][melons]", value: "2" }];
let newArray = [];
let result = [];
array.forEach((obj, i) => {
let nameArray = obj.name.replace(/[\[\]']+/g, ' ').trim().split(' ');
let o = {};
o['id'] = parseInt(nameArray[0]);
o[nameArray[1]] = obj.value;
newArray.push(o);
});
for(let i = 0; i< newArray.length; i++) {
for(let j = i+1; j < newArray.length; j++) {
if(newArray[i].id === newArray[j].id) {
let o = {...newArray[i], ...newArray[j]};
result.push(o);`enter code here`
}
}
}
console.log('Final result', result);
Thanks for the input. I think my question needed to be more specific:
(1) Yes, they are always in order.
(2) My names of my input-tags in html appear to be an multidimensional array. This is not the case! I tried something, but it turned out to be for php.
I found the follow workaround:
function apiAdapter() {
var arrayToCopy = $("#formsteps").serializeArray();
var copiedArray = [];
for (let i = 0; i < arrayToCopy.length; i += 2) {
var id = arrayToCopy[i].name.slice(arrayToCopy[i].name.indexOf('[') + 1, arrayToCopy[i].name.indexOf(']'));
copiedArray.push({ "id": id, "apples": arrayToCopy[i].value, "melons": arrayToCopy[i + 1].value })
}
return copiedArray;
}
As I am new to JavaScript I always look for better solutions. So thanks again for your posts.

Trying to nest dynamically generated JSON based on user input in Javascript

I am fairly new at manipulating and writing JSON objects etc and I have this task to dynaimcally create JSON object based on user input. I have managed to create the object at 1 level, but i want to nest objects within objects, this is the desired output
// desired output
masterObj = [
{
"Market1": {
"Size1": {
"id": 1,
"reporting_label": "a",
...
},
"Size2": {
"id": 2,
"reporting_label": "a",
...
},
"Size3": {
"id": 3,
"reporting_label": "a",
...
},
"Size4": {
"id": 4,
"reporting_label": "a",
...
},
"Size5": {
"id": 5,
"reporting_label": "a",
...
}
},
"Market2": {...},
"Market3": {...},
"Market4": {...}
}
]
I am trying to use the push function on my masterObj and then in the for loop push the required objects into the child of the masterObj for each market. But all i can get to is having all objects on the same level (ie 9 objects), having started going round in circles now trying to solve this...
var masterObj = [{
}];
var requested = [
{
"Markets": {
// boolean values defined by checkboxes
"Market1": show_m1, "Market2": show_m2, "Market3": show_m3, "Market4": show_m4
},
"Sizes": {
// boolean values defined by checkboxes
"Size1": show_s1, "Size2": show_s2, "Size3": show_s3, "Size4": show_s4, "Size5": show_s5
}
}
]
for (var item of requested) {
if(item.Markets.Market1 === true ) {
var m1Obj = {Market1: {}}
masterObj.push(m1Obj);
if(item.Sizes.Size1 === true) {
var s1Obj = {
Size1: {}
}
masterObj.push(s1Obj);
}
if(item.Sizes.Size2 === true) {
var s2Obj = {
Size2: {}
}
sgObj.push(s2Obj);
}
if(item.Sizes.Size3 === true) {
var s3Obj = {
Size3: {}
}
sgObj.push(s3Obj);
}
if(item.Sizes.Size4 === true) {
var s4Obj = {
Size4: {}
}
masterObj.push(s4Obj);
}
if(item.Sizes.Size5 === true) {
var s5Obj = {
Size5: {}
}
masterObj.push(s5Obj);
}
}
if(item.Markets.Market2 === true ) {
var m2Obj = {
Market2: {}
}
// ouput each requested size
masterObj.push(m2Obj);
}
if(item.Markets.Market3 === true ) {
var m3Obj = {
Market3: {}
}
// ouput each requested size
masterObj.push(m3Obj);
}
if(item.Markets.Market4 === true ) {
var m4Obj = {
Market4: {}
}
// ouput each requested size
masterObj.push(m4Obj);
}
}
console.log(masterObj);
Any help with this would be amazing, In my head i believe I am close to the solution but at the moment its evading me!
Push won't work because your object has an array of one element.. which is an object not an array
masterObj = [ { ... } ]
More than likely you mean to have this kind of a construct:
masterObj = {
"Market1": {
"Size1": {
"id": 1,
"reporting_label": "a",
...
},
"Size2": {
"id": 2,
"reporting_label": "a",
...
},
"Size3": {
"id": 3,
"reporting_label": "a",
...
},
"Size4": {
"id": 4,
"reporting_label": "a",
...
},
"Size5": {
"id": 5,
"reporting_label": "a",
...
}
},
"Market2": {...},
"Market3": {...},
"Market4": {...}
}
which you can then access with
masterObj.Market7 = {...};
Or, if you need to access through a variable:
key = 'Market7';
masterObj[key] = {...};
EDIT: Note: JSONS has nothing to do with this question. You are dealing with straight objects and arrays. JSON applies only when you serialize/deserialize this object into a string -- usually for storage or transport.
With a little restructuring this is the code i have ended up with and I am now getting what i needed.
thanks Jeremy for pointing me in the right direction.
var requestedMarkets = [
{market: "Market1", display: show_m1, name: "m1"},
{market: "Market2", display: show_m2, name: "m2"},
{market: "Market3", display: show_m3, name: "m3"},
{market: "Market4", display: show_m4, name: "m4"}
];
var requestedSizes = [
{display: show_s1, size: '100x200', name: "S1"},
{display: show_s2, size: '100x300', name: "S2"},
{display: show_s3, size: '100x400', name: "S3"},
{display: show_s4, size: '100x500', name: "S4"},
{display: show_s5, size: '100x600', name: "S5"}
];
for (let item of requestedMarkets) {
if(item.display === true ) {
masterObj[item.market] = {};
for (let size of requestedSizes) {
var settings = {
id: uniqueID,
...
}
if(size.display === true) {
masterObj[item.market][size.name] = settings;
}
}
}
}
console.log(masterObj);

Javascript get parent of item in array

I am trying to get the parent of a specific (referenced) object in an array.
Example:
var data = [
{
key: "value1"
children: [
{
key: "value2"
},
{
key: "value3"
children: [
{
key: "value3a"
},
{
key: "value3b"
}
]
}
]
},
{
key: "value4"
}
];
When some stuff happens, I get the following:
var clicked = {
key: "value3a"
}
In this case I know that value3a has been clicked, and it's databound with the data variable.
The question is, how do I easily get the parent of clicked? It should return the whole children-array of value3 which I want:
[
{
key: "value3a"
},
{
key: "value3b"
}
]
Note: currently I am using UnderscoreJS to find the object of my array. So maybe UnderscoreJS could help?
Just create a child-parent map so that you can look up what you need:
var map = {};
function recurse(arr, parent) {
if (!arr) return;
for (var i=0; i<arr.length; i++) { // use underscore here if you find it simpler
map[arr[i].key] = parent;
recurse(arr[i].children, arr[i]);
}
}
recurse(data, {key:"root", children:data});
Now, in your event handler you can trivially use that map to look up your siblings:
map[clicked.key].children
You could use a recursive reduce function.
// Given
var data = [
{
key: "value1",
children: [
{
key: "value2"
},
{
key: "value3",
children: [
{
key: "value3a"
},
{
key: "value3b"
}
]
}
]
},
{
key: "value4"
}
];
var clicked = {
key: "value3a"
};
We can define a recursive reduce function, and give it the parent
as the context.
var rec_reduce = function(memo, obj) {
if(obj.key == clicked.key) {
return this || memo;
}
return _.reduce(obj.children, rec_reduce, memo, obj.children) || memo;
};
// Now we can lookup the key in clicked with one line
_.reduce(data, rec_reduce, null, data);
// Returns [{key: "value3a"}, {key: "value3b"}]
Or, if you want to leverage underscore to make a map as suggested in the first answer, that is even simpler:
var map = {};
var rec_map = function(obj, i, parent) {
map[obj.key] = parent;
_.each(obj.children, rec_map);
};
_.each(data, rec_map);
// Now getting the parent list is just a look up in the map
map[clicked.key]
// Returns [{key: "value3a"}, {key: "value3b"}]

Create object array by pushing variables?

I am trying to create something like
var[1] = {object1, object2};
var[2] = {object1, object3);
Or something like that so that I can loop over each result and get all the objects associated with that key. The problem is I am either really tried or something because I can't seem to figure out how to do that.
In PHP I would do something like
$var[$object['id']][] = object1;
$var[$object['id']][] = object2;
How can I do something like that in Javascript?
I have a list of object elements, that have a key value called id and I want to organize them all by ID. Basically...
[0] = { id: 2 },
[1] = { id: 3 },
[2] = { id: 2 },
[3] = { id: 3 }
And I want to have them organized so it is like
[0] = { { id: 2 }, { id: 2 } }
[1] = { { id: 3 }, { id: 3} }
var indexedArray = [];
for(var key in myObjects) {
var myObject = myObjects[key];
if(typeof(indexedArray[myObject.id]) === 'undefined') {
indexedArray[myObject.id] = [myObject];
}
else {
indexedArray[myObject.id].push(myObject);
}
}
console.log(indexedArray);
http://jsfiddle.net/2fr4k/
Array is defined by square brackets:
var myArray = [{ "id": 2 }, { "id": 3 }];
What you had is not a valid syntax.
Using ECMA5 methods, you could do something like this.
Javascript
var d1 = [{
id: 2
}, {
id: 3
}, {
id: 2
}, {
id: 3
}],
d2;
d2 = d1.reduce(function (acc, ele) {
var id = ele.id;
if (!acc[id]) {
acc[id] = [];
}
acc[id].push(ele);
return acc;
}, {});
d2 = Object.keys(d2).map(function (key) {
return this[key];
}, d2);
console.log(JSON.stringify(d2));
Output
[[{"id":2},{"id":2}],[{"id":3},{"id":3}]]
On jsFiddle

Finding matching objects in an array of objects?

var set = [{"color":"blue"},{"color":"green"},{"color":"red"},{"color":"green"}];
I'd like to be able to do something like a db call, set.find({"color":"green"}) and have it return an array full of objects that contain that property.
Using Array#filter, for this particular case the code would look like
var results = set.filter(function (entry) { return entry.color === "green"; });
Array#filter is not implemented in some older browsers, so see the linked article for a backward compatibility shim, or better yet get a full-fledged ES5 shim.
For the more general case, it's just a matter of extending this idea:
function findByMatchingProperties(set, properties) {
return set.filter(function (entry) {
return Object.keys(properties).every(function (key) {
return entry[key] === properties[key];
});
});
}
var results = findByMatchingProperties(set, { color: "green" });
Again, I am using ECMAScript 5 methods Object.keys and Array#every, so use an ES5 shim. (The code is doable without an ES5 shim but uses manual loops and is much less fun to write and read.)
I have used map function from jquery and I am getting selected index by passing searched key value so by using that index we will get required object from array.
var mydata = [{ name: "Ram", Id: 1 }, { name: "Shyam", Id: 2 }, { name: "Akhil", Id: 3 }];
searchKey = 2
var mydata = [{ name: "Ram", Id: 1 }, { name: "Shyam", Id: 2 }, { name: "Akhil", Id: 3 }];
searchKey = 2
var selectedData = mydata[mydata.map(function (item) { return item.Id; }).indexOf(searchKey)];
console.log(selectedData)
var selectedData = mydata[mydata.map(function (item) { return item.Id; }).indexOf(searchKey)];
console.log(selectedData)
output
{ name: "Shyam", Id: 2 }
Note: if you want to pass search key as object then
searchKey = { Id: 2 };
mydata[mydata.map(function (item) { return item.Id; }).indexOf(searchKey.Id)];
output
{ name: "Shyam", Id: 2 }
Using arrow functions with an implied return and concise body:
const results = set.filter(entry => entry.color === "green");
Another example passing in a search variable:
const searchString = 'green';
const results = set.filter(entry => entry.color === `${searchString}`);
Read more about arrow functions on
MDN
Since you've included the jQuery tag, here's one way to do it using jQuery's map:
var results = $.map( set, function(e,i){
if( e.color === 'green' ) return e;
});
The documentation states that you need to return null to remove the element from the array, but apparently this is false, as shown by the jsFiddle in the comments; returning nothing (i.e. returning undefined) works just as well.
I went with a different approach that I found to be a bit easier.
function isObjEqual(a, b) {
const x = JSON.stringify(a);
const y = JSON.stringify(b);
return x === y;
}
// Example 1
const set = [{"color":"blue"},{"color":"green"},{"color":"red"},{"color":"green"}];
const findObj1 = {"color":"green"};
const arr1 = set.filter((objInArr) => isObjEqual(objInArr, findObj1));
console.log(arr1) // [ { color: 'green' }, { color: 'green' } ]
// Example 2
const list = [{
"label": "Option 2",
"value": "option2"
},
{
"label": "Option 3",
"value": "option3"
},
{
"label": "Option 2",
"value": "option2"
}
];
const findObj2 = {
"label": "Option 2",
"value": "option2"
}
const newList = list.filter((objInArr) => isObjEqual(objInArr, findObj2));
console.log(newList) //[ { label: 'Option 2', value: 'option2' }, { label: 'Option 2', value: 'option2' } ]

Categories

Resources