Other than just iterating over the unassociated array and manually adding them, how does one merge an unassociated array with serialized name/value pairs?
//I select some values
var data = $('#mytable input:checked');
console.log(data); //Object[input attribute value = "1", input attribute value = "3"]
//I get some extra values I wish to send to the server
var types = data.map(function() {
return $(this).data("types");
}).get();
console.log(types); // ["type1", "type3"]
//I serialize data
data = data.serializeArray();
console.log(data); // [Object { name="id[]", value="1"}, Object { name="id[]", value="3"}]
//I add an extra value
data.push({
name: "task",
value: 'restoreRecord'
})
console.log(data); // [Object { name="id[]", value="1"}, Object { name="id[]", value="3"}, Object { name="task", value="restoreRecord"}]
/*
How do I merge data and types so that I come up with the following:
[
Object { name="id[]", value="1"},
Object { name="id[]", value="3"},
Object { name="types[]", value="type1"},
Opject { name="types[]", value="type3"},
Object { name="task", value="restoreRecord"}
]
*/
You can run a for loop over types and add values from it to data
// I want to merge this
var data = [{
name: "id[]",
value: "1"
}, {
name: "id[]",
value: "3"
}, {
name: "task",
value: "restoreRecord"
}];
// with this
var types = ['type1', 'type2'];
for(var i = 0; i < types.length; i++){
data.push({
name: 'types[]',
value: types[i]
});
}
console.log(data);
Related
how to get the value in any way if key does match with "Item"
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
console.log(data[i].includes("Item"));
//Expecting phone and case
}
for-in allows you to loop through the keys in an object. Not to be confused with for-of, which loop through elements in an array.
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
for(let datum of data)
{
for(let key in datum)
{
if(key.includes("Item"))
{
console.log(datum[key]);
}
}
}
In the simple way just change data[i].includes("Item") to data[i].keys().includes("Item").
BUT! Could we have some alternative data set here? For example:
const data = [{
"Item-55566": "phone",
"SomeKey: "Some Value",
123123: "Numeric key with value"
},
{
"Items-44555": "Case",
"Another-key": "Another value"
}
];
In this case you need to put some changes in your code to find correct keys & values:
for(let i = 0; i<data.length; i++) {
data[i].keys().forEach(v=>{
String(v).includes("Item") && console.log("Got index: ${i}, key: ${v}, value: ${data[i][v]}")
})
}
The for loop iterates through the two objects, so you can check to see whether the object has that particular property using hasOwnProperty()
const data = [
{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
},
];
/* How to get value if index found by Item */
for (let i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty("Item-55566")) {
console.log(data[i]);
}
}
If you want to keep your loop (good that it's only one loop compared to other answers) you can do it with Object.keys and values:
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
if(Object.keys(data[i])[0].includes('Item')){
console.log(Object.values(data[i])[0]);
}
}
You can use .filter to filter all items of the data array which includes Item text.
Then you can use .map to render new value from each object comes from data array.
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var filteredItems = data.filter(item => Object.keys(item)[0].includes("Item"));
console.log(filteredItems.map(item => Object.values(item)[0]));
Refactor code - By using .reduce()
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var res = data.reduce((prev, curr) =>
{
var entries = Object.entries(curr)[0];
if(entries[0].includes("Item"))
prev.push(entries[1]);
return prev;
}, []);
console.log(res);
I have the array of Objects as follows
Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id=1
name: "Rick"
Value: "34343"
1:Object
id=2
name:'david'
Value: "2332"
As you can see, the Value field in the array of Objects is a string. I want all these to be converted to a number instead.
The final data should look like this. can someone let me know how to achieve this please.
Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id=1
name: "Rick"
Value: 34343
1:Object
id=2
name:'david'
Value: 2332
You can convert a number literal into a number using a + prefix:
var input = {
Results: [{
id: 1,
name: "Rick",
Value: "34343"
}, {
id: 2,
name: 'david',
Value: "2332"
}]
}
for (var i = 0; i < input.Results.length; i++) {
input.Results[i].Value = +input.Results[i].Value;
}
console.log(input);
Just call .parseInt() on each of your "Value" fields. For example: `
for(var i in Results){
if(Results[i].Value != ""){
Results[i].Value = parseInt(Results[i].Value);
}`
}
You can map data.Results and use parseInt() on the Value properties:
data.Results = data.Results.map(function(d) {
d.Value = parseInt(d.Value, 10);
return d;
});
console.log(data);
However, why do you need this? Maybe you should consider to do the parsing once you actually access the data...
If you can do this in a basic way, it will look like:
function convertArrayValues (array) { // obj.Results goes here
// cloning can be ommited
var array = JSON.parse(JSON.stringify(array));
for(var i = 0; i < array.length; i++) {
array[i].Value = parseFloat(array[i].Value);
}
return array;
}
How to sort array by num property in this JavaScript array.
var data = [{
005: { `num`: 1360487},
047: { `num`: 2519472},
061: { `num`: 1559115},
081: { `num`: 2232710},
085: { `num`: 54956 }
}];
What you are manipulating is an array containing 1 object, not an array of objects. You should probably change the structure of data to make it easier to manipulate, an example would be:
var data = [
[005, { num: 1360487}],
[047, { num: 2519472}],
[061, { num: 1559115}],
[081, { num: 2232710}],
[085, { num: 54956 }],
];
data.sort(
function (firstElem, secondElem) {
return firstElem[1].num - secondElem[1].num;
}
);
// data is sorted
I got two data structures in different formats.
The first:
{loginRememberMe: false, test: false}
The second:
[
{
Objectname: "loginEmail",
value: "one"
},
{
Objectname: "loginPassword",
value: "two"
}
]
I am trying to convert the first structure to match the format of the second structure and to then merge them.
This needs to be done using JavaScript / jQuery,
In future please show the final structure you need to have. You cannot directly merge an Object with an Array.
var first = {
loginRememberMe: false,
test: false
}
var second = [{
Objectname: "loginEmail",
value: "one"
}, {
Objectname: "loginPassword",
value: "two"
}]
var modifiedArray = addObjectKeysToArray(second, first);
console.log( modifiedArray );
console.log( second );
console.assert(second !== modifiedArray, 'both arrays should be different');
function addObjectKeysToArray(arr, obj) {
// copy the arr so we don't modify the original
var arrCopy = arr.slice(0);
// loop through the object properties
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// add to the copied array
arrCopy.push({
Objectname: key,
value: obj[key]
});
}
}
return arrCopy;
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
You can use:
myArray.push({
Objectname: Object.keys(myObject)[0],
value: Object.keys(myObject)[1]
})
if you want to get this array:
[
{
Objectname: "loginEmail",
value: "one"
},
{
Objectname: "loginPassword",
value: "two"
},
{
Objectname: "loginRememberMe",
value: "false"
}
]
and your array of objects is called myArray and the object you want to merge into array is called myObject.
Check demo: Fiddle
(context)I have information from a bunch of elements that I'm collecting into a JSON object that then gets passed down to an MVC3 controller where it gets deserialized into an object.
There are 'items' and 'item settings'. Currently, I have have both items and item settings all in flat JSON object. Ideally I would like to have the item settings nested under each item. My code currently looks like this:
var editeditems=[];
...
$("#SaveChanges").click(function() {
//this works and retrieves all of the item IDs
$(".portlet").each(function() {
var itemname = $(this).data("itemname");
editeditems.push(
{
"itemname": itemname
});
itemname = $(this).data("itemname");
$(".settingInput").each(function() {
editeditems.push(
{
"settingkey":$(this).attr("name"),
"settingvalue":$(this).attr("value")
});
});
});
Under the $(".settingInput").each function is where the settings get added. I've tried syntax like 'editedItems.settings.push..' but it returns with a syntax error.
Any help would greatly be appreciated!
var editeditems = [];
...
$('#SaveChanges').click(function() {
$('.portlet').each(function() {
var settings = [];
$('.settingInput').each(function() {
settings.push({
settingkey: $(this).attr('name'),
settingvalue: $(this).attr('value')
});
});
editeditems.push({
itemname: $(this).data('itemname'),
settings: settings
});
});
...
});
will generate sample output:
var editeditems =
[
{
"itemname": "item1",
"settings": [
{
"settingkey": "key1",
"settingvalue": "value1"
},
{
"settingkey": "key2",
"settingvalue": "value2"
}
]
},
{
"itemname": "item2",
"settings": [
{
"settingkey": "key1",
"settingvalue": "value3"
},
{
"settingkey": "key2",
"settingvalue": "value4"
}
]
}
];
var ei = {'settings': [3]};
ei.settings.push(4);
console.log(ei);
// This will output an object with property settings and value an array with values (3 and 4)
You need to create flat data array json as:
[{"itemname": "item1","settingkey": "key1","settingvalue": "value1"},
{"itemname": "item2","settingkey": "key2","settingvalue": "value2"},];
Than process the above date like this
var keys = Object.keys(dataMap);
var json = [];
for (var key in keys) {
var innerJson = {};
innerJson["name"] = keys[key];
var innerMap = dataMap[keys[key]];
if (innerMap instanceof Array) {
innerJson["size"] = innerMap[0];
} else if (innerMap instanceof Object) {
var child = processHirarchiachalData(innerMap);
innerJson["children"] = child;
}
json.push(innerJson);
}