I tried to update the source of Autocomplete, but after I update it, it could not show the list of the source? Did I do anything wrong here?
Here is my set up:
let cities = [
{"label":"Alessandria","id":"AL"},
{"label":"Milano","id":"MI"},
{"label":"Pisa","id":"PI"},
{"label":"Pistoia","id":"PT"}
];
test_auto_c(cities); //For the first time, set up autocomplete.
$("#btn1").click(() => {
let arr = [
{"lable": "Changed1-1", "id": "1"},
{"lable": "Changed1-2", "id": "2"},
{"lable": "Changed1-3", "id": "3"}
];
$("#autocomplete-city").autocomplete('option', 'source', arr); //change the source
});
$("#btn2").click(() => {
let arr = [
{"lable": "Changed2-1", "id": "4"},
{"lable": "Changed2-2", "id": "5"},
{"lable": "Changed2-3", "id": "6"}
];
$("#autocomplete-city").autocomplete('option', 'source', arr); //change the source
});
Below is the function of test_auto_c():
function test_auto_c(arr){
$("#autocomplete-city").autocomplete({
source: arr,
minLength: 0,
select: function(event, ui){
if(ui.item){
return ui.item.label;
}
else{}
},
change: function(event, ui){
var searched = this.value;
if(ui.item){
}
else{
var result = arr.filter(function( obj ) {
return obj.label.toLowerCase().indexOf(searched.toLowerCase()) !== -1;
});
if(result.length>0){
$(this).val(result[0].label);
}
else{
//clear the autocomplete
let final_value = arr[0].label;
$(this).val(final_value);
}
}
}
}).focus(function () {
$(this).autocomplete("search");
});
}
finally, it gives me the result of empty list after I tried to change the source.
What I expect is display like below:
And I am using:
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
First you have to review the docs:
Multiple types supported:
Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
It seems to work and when you then change the source later, it does not work. This is due to a typo, you have "lable" where you need "label".
$(function() {
function test_auto_c(arr) {
$("#autocomplete-city").autocomplete({
source: arr,
minLength: 0
}).focus(function() {
$(this).autocomplete("search");
});
}
let cities = [{
"label": "Alessandria",
"id": "AL"
},
{
"label": "Milano",
"id": "MI"
},
{
"label": "Pisa",
"id": "PI"
},
{
"label": "Pistoia",
"id": "PT"
}
];
test_auto_c(cities);
$("#btn1").click(() => {
let arr = [{
"label": "Changed1-1",
"id": "1"
},
{
"label": "Changed1-2",
"id": "2"
},
{
"label": "Changed1-3",
"id": "3"
}
];
$("#autocomplete-city").autocomplete('option', 'source', arr); //change the source
});
$("#btn2").click(() => {
let arr = [{
"label": "Changed2-1",
"id": "4"
},
{
"label": "Changed2-2",
"id": "5"
},
{
"label": "Changed2-3",
"id": "6"
}
];
$("#autocomplete-city").autocomplete('option', 'source', arr); //change the source
});
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<div>
<input type="text" id="autocomplete-city">
<button id="btn1">Btn 1</button>
<button id="btn2">Btn 2</button>
</div>
Related
Currently, I was trying to make multiple chain dropdown lists.
The data was json format something like.
[{"y":1,"x":1,"name":"5M","value":0},
{"y":1,"x":2,"name":"5L","value":2},
{"y":1,"x":3,"name":"5K","value":16},
{"y":1,"x":4,"name":"5J","value":0},
{"y":1,"x":5,"name":"5H","value":0},
{"y":1,"x":6,"name":"5G","value":1},
{"y":1,"x":7,"name":"5F","value":8},
The dropdown idealized was like the footer filter of this example from datatable.
http://live.datatables.net/gejojiqu/1/edit
All of the dropdown select lists can be dynamic dependent after one or many attributes (column) were selected.
For example like when I select the 1st dropdown list which belongs to the "name" attribute with "Bradley Greer", the "position" dropdown select value will only remain "Software Engineer" and so on the other dropdown select value.
Any idea or guidance that how can I achieve this dropdown?
I search for a lot of related guidance about cascading dropdowns non of their data format was similar to mine.
Any help was appreciated.
I manage to find the solution by myself by using jQuery and struggling for a night:
const my data = [
{
"Data": "aaa",
"Media": "1",
"Row": "1",
"Column": "3",
"Code": "24",
},
{
"Data": "aaa",
"Media": "2",
"Row": "1",
"Column": "1",
"Code": "24",
},
{
"Data": "aba",
"Media": "3",
"Row": "1",
"Column": "3",
"Code": "24",
},
{
"Data": "aab",
"Media": "4",
"Row": "1",
"Column": "2",
"Code": "24",
},
{
"Data": "aab",
"Media": "1",
"Row": "2",
"Column": "1",
"Code": "24",
},
{
"Data": "aab123",
"Media": "1",
"Row": "2",
"Column": "1",
"Code": "23",
},
]
mydata.forEach(function(row,index) {
mydata[index] = Object.values(mydata[index]);
});
function makeDropDown(data,filtersAsArray,targetElement){
const filteredArray = filterArray(data, filtersAsArray);
const uniqueList = getUniqueValues(filteredArray,filtersAsArray.length);
populateDropDown(targetElement,uniqueList);
}
function applyDropDown(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2 = document.getElementById("level2");
makeDropDown(mydata, [selectLevel1Value], selectLevel2);
applyDropDown2();
applyDropDown3();
applyDropDown4();
}
function applyDropDown2(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2Value = document.getElementById("level2").value;
const selectLevel3 = document.getElementById("level3");
makeDropDown(mydata, [selectLevel1Value, selectLevel2Value], selectLevel3);
}
function applyDropDown3(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2Value = document.getElementById("level2").value;
const selectLevel3Value = document.getElementById("level3").value;
const selectLevel4 = document.getElementById("level4");
makeDropDown(mydata, [selectLevel1Value, selectLevel2Value, selectLevel3Value], selectLevel4);
}
function applyDropDown4(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2Value = document.getElementById("level2").value;
const selectLevel3Value = document.getElementById("level3").value;
const selectLevel4Value = document.getElementById("level4").value;
const selectLevel5 = document.getElementById("level5");
makeDropDown(mydata, [selectLevel1Value, selectLevel2Value, selectLevel3Value, selectLevel4Value], selectLevel5);
}
function afterDocumentLoads(){
populateFirstLevelDropDown();
applyDropDown();
}
function getUniqueValues(data,index){
const uniqueOptions = new Set();
data.forEach(r => uniqueOptions.add(r[index]));
return [...uniqueOptions];
}
function populateFirstLevelDropDown(){
const uniqueList = getUniqueValues(mydata,0);
const el = document.getElementById("level1");
populateDropDown(el,uniqueList);
}
function populateDropDown(el,listasArray){
el.innerHTML = "";
listasArray.forEach(item => {
const option = document.createElement("option");
option.textContent = item;
el.appendChild(option);
});
}
function filterArray(data, filtersAsArray){
return data.filter(r => filtersAsArray.every((item,i) => item === r[i]));
}
document.getElementById("level1").addEventListener("change",applyDropDown);
document.getElementById("level2").addEventListener("change",applyDropDown2);
document.addEventListener("DOMContentLoaded", afterDocumentLoads);
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<label>Data</label>
<select class="js-example-basic-single" id="level1" name="level1"></select>
<label>Media</label>
<select class="js-example-basic-single" id="level2" name="level2"></select>
<label>Row</label>
<select class="js-example-basic-single" id="level3" name="level3"></select>
<label>Column</label>
<select class="js-example-basic-single" id="level4" name="level4"></select>
<label>Code</label>
<select class="js-example-basic-single" id="level5" name="level5"></select>
Fiddle
I want to receive the dependency string from the dataDependencyMap.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<script>
var data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2, "type": "critical" },
{"id": 3, "type": "moderate"}
]
},
{
"id": 2,
"active": true,
"dependency":[
{"id": 3, "type": "moderate"}
]
},
{
"id": 3,
"active": false,
"dependency":[]
}
]
// this works as it should
var dataActiveMap = new Map(data.map(obj => [obj.id, obj.active]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true ) {
console.log(id, "active: ", true)
}
})
// HERE IS THE PROBLEM: How can I return the dependency string, like "critical" or "moderate"
var dataDependencyMap = new Map(data.map(obj => [obj.id, obj.dependency]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true) {
console.log(id, "dependency: ", dependency.value)
}
})
</script>
</html>
There is no value property of dependency, you can pass dependency so that you can access that object like the following way:
<script>
var data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2, "type": "critical" },
{"id": 3, "type": "moderate"}
]
},
{
"id": 2,
"active": true,
"dependency":[
{"id": 3, "type": "moderate"}
]
},
{
"id": 3,
"active": false,
"dependency":[]
}
]
// this works as it should
var dataActiveMap = new Map(data.map(obj => [obj.id, obj.active]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true ) {
//console.log(id, "active: ", true)
}
})
// HERE IS THE PROBLEM: How can I return the dependency string, like "critical" or "moderate"
var dataDependencyMap = data.map(({id, dependency}) => ({id, dependency}));
data.forEach(function({id, dependency}) {
if (dataActiveMap.get(id) == true) {
//console.log(id, "dependency: ", dependency);
// if you need the *type* property as comma separated string
console.log("id:", id, "and dependency:", dependency.map(({type}) => type).join(', '));
}
})
</script>
I'm not sure what the dataActiveMap constant would be used for but an alternative solution would be to use for loops. If you still need the dataActiveMap and dataDependencyMap, you can always create those arrays and use the push() method to add the values to the arrays at appropriate times in the loops. Check the solution below.
for (key in data){ // loops through the data array
// console.log(data[key])
if (data[key].active) // checks if each object's active property in data array is true
{
// console.log(data[key].dependency)
for (dependency in data[key].dependency) // loops through dependencies
{
// console.log(data[key].dependency[dependency])
for (props in data[key].dependency[dependency]) // loops through objects nested in dependencies
{
console.log(data[key].dependency[dependency].type) //prints the type property
}
}
}
}
I have a JSON object like below (dataSource) in that JSON object the property 'viewClasses' sometimes comes as blank, here what I want to do is if 'viewClasses' have any record I want to add a dynamic column to the table and the name of the column header will be the value of 'viewClasses.class', I have tried the below code but it's not working as expected.
Here is the result of the below code -
Here how I want this to be-
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var column = [];
function AddColumn() {
$.each(dataSource[0].viewDetails.viewClasses[0], function(key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
column.push(my_item);
});
}
$('#example').dataTable({
data: dataSource[0].viewDetails.viewClasses,
"columns": column,
"paging": false,
"bInfo": false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<style src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"></style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="example" class="table table-striped" width="100%"></table>
</div>
</div>
</div>
Your source data needs to be iterated in two different ways, to build the two different dynamic arrays which DataTables needs: - column data and row data.
Firstly you have two columns, A and B. To build the array for these, you can use the following:
var dynamicColumns = [];
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
});
I chose not to use the jQuery iterator because I want access to each object in the array.
This gives me the following structure:
[
{
"data": "A",
"title": "Heading A"
},
{
"data": "B",
"title": "Heading B"
}
]
But for the table's data, I want to end up with only one row of data:
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
Here, I end up with the following:
[
{
"A": 2000,
"B": 3000
}
]
Now I have the structures I need for my DataTable initialization. The overall script therefore is as follows:
<script type="text/javascript">
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var dynamicColumns = [];
var dynamicRows = [];
function buildDynamicData() {
var columnData = dataSource[0].viewDetails.viewClasses;
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
}
buildDynamicData();
console.log(dynamicColumns);
console.log(dynamicRows);
$(document).ready(function() {
$('#example').DataTable({
columns: dynamicColumns,
data: dynamicRows,
paging: false,
info: false
});
} );
</script>
And the end result looks like this (in my test environment):
I have this data from a csv file that i have to use in a dependant dropdown with jquery. I can't figure out if it is possible to nest the data i received for what i already have coded.
CSV file
Banco Tarjeta Cuotas Medio_Pago Coeficiente TEA CFT
Santander Visa 1 modulodepago2 1 0.00% 0.00%
Santander Visa 1 nps 1.0262 18.56% 22.84%
Frances Visa 1 modulodepago2 1 0.00% 0.00%
Frances Master 2 nps 1.0262 18.56% 22.84%
My json data comes like this
[{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"modulodepago2",
"coeficiente":"1","tea":"0.00%","cft":"0.00%"},
{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"nps",
"coeficiente":"1.0262","tea":"18.56%","cft":"22.84%"} ...
etc...
Is there a way i can nest this json data like this (+ adding unique names and id's)?
var myJson = {
"banco": [
{
"name": "Santander",
"id": "Santander",
"tarjeta": [
{
"name": "Visa",
"id": "SantanderVisa",
"cuotas": [
{
"name": "1",
"id": "SantanderVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
},
{
"name": "1",
"id": "SantanderVisa2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
},
{
"name": "Frances",
"id": "Frances",
"tarjeta": [
{
"name": "Visa",
"id": "FrancesVisa",
"cuotas": [
{
"name": "1",
"id": "FrancesVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
}
]
},
{
"name": "Master",
"id": "FrancesMaster",
"cuotas": [
{
"name": "2",
"id": "FrancesMaster2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
}
]
}
You will need to group by keys. An easy way to do this is to use Lodash or Underscore.js.
I used Papa Parse to convert the CSV data into JSON.
var csvData = $('#csv-data').text().trim();
var jsonData = Papa.parse(csvData, { delimiter:',', header:true }).data;
var transformedJson = {
banco : _.chain(jsonData)
.groupBy('Banco')
.toPairs()
.map(banco => {
return {
name : banco[0],
id: banco[0],
tarjeta : _.chain(banco[1])
.groupBy('Tarjeta')
.toPairs()
.map(tarjeta => {
return {
name: tarjeta[0],
id: banco[0] + tarjeta[0],
cuotas: _.map(tarjeta[1], cuota => {
return {
name: cuota['Cuotas'],
id: banco[0] + tarjeta[0] + cuota['Cuotas'],
medio_pago: cuota['Medio_Pago'],
coeficiente: cuota['Coeficiente'],
tea: cuota['TEA'],
cft: cuota['CFT']
}
})
};
})
}
}).value()
}
console.log(JSON.stringify(transformedJson, null, 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.4/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<textarea id="csv-data" style="display:none" rows="5" cols="72">
Banco,Tarjeta,Cuotas,Medio_Pago,Coeficiente,TEA,CFT
Santander,Visa,1,modulodepago2,1,0.00%,0.00%
Santander,Visa,1,nps,1.0262,18.56%,22.84%
Frances,Visa,1,modulodepago2,1,0.00%,0.00%
Frances,Master,2,nps,1.0262,18.56%,22.84%
</textarea>
try something like this
you get all medio_pago for the others objects you just use the object name.
I haven't tested it but I'm sure this will work for you.
var Json = ...
$.each(Json, function(i, item) {
alert(myJson[i].banco.tarjeta.cuotas.medio_pago);
});
I have this sample JSON object
var sample = [{
"label": "one",
"value": 1
}, {
"label": "two",
"value": 2
}, {
"label": "three",
"value": 3
}, {
"label": "four",
"value": 4
}, {
"label": "five",
"value": 5
}];
I want to change it some thing like this
var sample = [{
"label": "one",
"value": 1,
"newKeyValue": "one|1"
}, {
"label": "two",
"value": 2,
"newKeyValue": "two|2"
}, {
"label": "three",
"value": 3,
"newKeyValue": "three|3"
},
...
];
It should combine both key values and return new key value combining both.
JSON is coming dynamically key label and value are not static it can be anything. For example [{"name":"srinivas","lastname":"pai"}]
You can use map like this :
EDIT
For handling generic keys you can use
Object.keys(d)[0] for first key
Object.keys(d)[1] for second key
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
var data = sample.map(function(d){
return {label: Object.keys(d)[0], value: Object.keys(d)[1], newKeyValue: Object.keys(d)[0] +"|" + Object.keys(d)[1]}
})
console.log(data)
Hope this helps!
You can use Array#map(), Object.keys(), and Array#join().
In ES6, you can use Arrow functions.
sample = sample.map(obj => {
var keys = Object.keys(obj);
obj.newKeyValue = keys.map(key => obj[key]).join('|');
return obj;
});
var sample = [{
"label": "one",
"value": 1
}, {
"name": "two",
"age": 2
}, {
"five": "three",
"six": 3
}, {
"company": "four",
"organization": 4
}, {
"label": "five",
"value": 5
}];
sample = sample.map(function (x) {
var keys = Object.keys(x);
x.newKeyValue = keys.map(key => x[key]).join('|');
return x;
});
console.log(sample);
document.body.innerHTML = '<pre>' + JSON.stringify(sample, 0, 4) + '</pre>';
In ES5, you can use the same code with anonymous functions
sample = sample.map(function (obj) {
var keys = Object.keys(obj);
obj.newKeyValue = keys.map(function (key) {
return obj[key]
}).join('|');
return obj;
});
Limitations due to dynamic keys:
The order of the keys in object cannot be maintained
This will join all the available keys in the object (in case if you just want to join fewer)
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2,
"optionalValue":2
},
{
"label":"three",
"value":3,
"remarks":"free text"
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
for (var key in sample) {
var newValue = [];
for (var piece in sample[key]){
newValue.push(sample[key][piece])
}
sample[key]["newKeyValue"] = newValue.join('|');
}
$('pre').html(JSON.stringify(sample,null,4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
You can use Array.prototype.forEach() for in situ changes.
The forEach() method executes a provided function once per array element.
Edit: with dynamic keys, stored in an array, because of the order.
var sample = [{ "label": "one", "value": 1 }, { "label": "two", "value": 2 }, { "label": "three", "value": 3 }, { "label": "four", "value": 4 }, { "label": "five", "value": 5 }];
sample.forEach(function (a) {
a.newKeyValue = ['label', 'value'].map(function (k) { return a[k]; }).join('|');
});
document.write('<pre>' + JSON.stringify(sample, 0, 4) + '</pre>');
If more element are their then use $.extend
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
$(sample).each(function(i,item){
var keyes = Object.keys(item);
sample[i] = $.extend(item,{newKeyValue: item[keyes[0]] +"|" +item[keyes[1]]});
});
console.log(sample)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$.extend also helpful when you are having more objects already and you want to merge both
eg.
var base = {
"label":"one",
"value":1
}
and you want to add more objects
var extra = {
"new1":"value1",
"new2":"value2",
"new3":"value3",
"new4":"value4",
}
then it will be done by
$.extend(base,extra);
Output:
{
"label":"one",
"value":1,
"new1":"value1",
"new2":"value2",
"new3":"value3",
"new4":"value4",
}
var sample = [{"name":"srinivas","lastname":"pai"}];
sample.map(function(item) {
item.newKeyValue = Object.getOwnPropertyNames(item).map(function(d) {return item[d];}).join("|");
})
console.log(sample);