How to Push the values in the array, using jquery - javascript

Trying to push the values into temp Array, from the existing array object. Here am validating whether the values are null or not in my existing object and then pushing it into temp Array.
But currently this is output I am getting : ["0","abc"]
Expected output should be [{"0":"abc"},{"1":"def"}]
Once the values are pushed into the temp array, I need to bind it to my html list.
This is what have tried.
JS:
var tempArray = [];
var json = [
{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}
]
for (var i=0;i<json.length;i++){
if(json[i].itemId!=""&&json[i].prodTitle!="")
tempArray.itemId = json[i].itemId;
tempArray.prodTitle = json[i].prodTitle;
tempArray.push(tempArray.itemId,tempArray.prodTitle);
}
console.log(tempArray);
Demo URL

You have many mistakes, here's right one
for (var i=0; i<json.length; i++){
if(json[i].itemId && json[i].prodTitle) {
tempArray.push(json[i]);
}
}
Your mistakes
for (var i=0;i<json.length;i++){
if(json[i].itemId!=""&&json[i].prodTitle!="") // <-- mistake, braces are needed, because you have 3 lines below
tempArray.itemId = json[i].itemId; // <-- you are adding property to array
tempArray.prodTitle = json[i].prodTitle; // <-- still adding
tempArray.push(tempArray.itemId,tempArray.prodTitle); //<-- pushing strings, not valid object, use like --> {key: value}
}

Another option using Array.filter Also makes it chain-able. However a for loop will be faster, depends if the chain-ability is something you require, i find it quite powerful at times.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var json = [
{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}
];
var tempArray = json.filter(function (item) {
return (isDefined(item.itemId) && isDefined(item.prodTitle));
});
function isDefined (o) {
return o !== undefined && o !== null && o !== '';
}
console.log(tempArray);
http://jsfiddle.net/zgg79wfa/1/

You can achieve this without jQuery by using the .filter() method:
var json = [{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}];
console.log( json );
var tempArray = json.filter( function( el ) {
return el.itemId && el.prodTitle;
});
console.log( tempArray );

Related

How to remove complete unique value from array [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 3 years ago.
How to remove complete record of same object in array please help me this, I am using below funtion but its only remove one value I want remove complete object of same object
var data = [{
"QuestionOid": 1,
"name": "hello",
"label": "world"
}, {
"QuestionOid": 2,
"name": "abc",
"label": "xyz"
}, {
"QuestionOid": 1,
"name": "hello",
"label": "world"
}];
function removeDumplicateValue(myArray) {
var newArray = [];
$.each(myArray, function (key, value) {
var exists = false;
$.each(newArray, function (k, val2) {
if (value.QuestionOid == val2.QuestionOid) { exists = true };
});
if (exists == false && value.QuestionOid != undefined) { newArray.push(value); }
});
return newArray;
}
I want result like this
[{
"QuestionOid": 2,
"name": "abc",
"label": "xyz"
}]
You can use reduce.
var data = [{"QuestionOid": 1,"name": "hello","label": "world"}, {"QuestionOid": 2,"name": "abc","label": "xyz"}, {"QuestionOid": 1,"name": "hello","label": "world"}];
let op = data.reduce((op,inp)=>{
if(op[inp.QuestionOid]){
op[inp.QuestionOid].count++
} else {
op[inp.QuestionOid] = {...inp,count:1}
}
return op
},{})
let final = Object.values(op).reduce((op,{count,...rest})=>{
if(count === 1){
op.push(rest)
}
return op
},[])
console.log(final)
Do with Array#filter.Filter the array matching QuestionOid value equal to 1
var data = [{ "QuestionOid": 1, "name": "hello", "label": "world" }, { "QuestionOid": 2, "name": "abc", "label": "xyz" }, { "QuestionOid": 1, "name": "hello", "label": "world" }]
var res = data.filter((a, b, c) => c.map(i => i.QuestionOid).filter(i => i == a.QuestionOid).length == 1)
console.log(res)

Remove a particular name inside an array [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
{
"list": [{
"name": "car",
"status": "Good",
"time": "2018-11-02T03:26:34.350Z"
},
{
"name": "Truck",
"status": "Ok",
"time": "2018-11-02T03:27:23.038Z"
},
{
"name": "Bike",
"status": "NEW",
"time": "2018-11-02T13:08:49.175Z"
}
]
}
How do I remove just the car info from the array.
To achieve expected result, use filter option to filter out car related values
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
result.list.push(obj.list.filter(v => v.name !=='car'))
console.log(result)
codepen - https://codepen.io/nagasai/pen/MzmMQp
Option 2: without using filter as requested by OP
Use simple for loop to achieve same result
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
for(let i =0; i< obj.list.length; i++){
if(obj.list[i].name !== 'car' ){
result.list.push(obj.list[i])
}
}
console.log(result)
const obj = JSON.parse(jsonString);
let yourArray = obj.list;
let filteredArray = yourArray.filter(elem => elem.name !== "car");

How to add a new key to multiple indices of an array of objects?

I've got an array of three people. I want to add a new key to multiple objects at once based on an array of indices. Clearly my attempt at using multiple indices doesn't work but I can't seem to find the correct approach.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
}
];
array[0,1].title = "Manager";
array[2].title = "Staff";
console.log(array);
Which returns this:
[
{
"name": "Tom",
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
But I'd like it to return this.
[
{
"name": "Tom",
"title": "Manager"
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
You cannot use multiple keys by using any separator in arrays.
Wrong: array[x, y]
Correct: array[x] and array[y]
In your case, it will be array[0].title = array[1].title = "manager";
1st method::
array[0].title = "Manager";
array[1].title = "Manager";
array[2].title = "Staff";
array[0,1] will not work.
2nd method::
for(var i=0;i<array.length;i++) {
var msg = "Manager";
if(i===2) {
msg = "Staff"
}
array[i].title = msg
}
You can use a helper function like this
function setMultiple(array, key, indexes, value)
{
for(i in array.length)
{
if(indexes.indexOf(i)>=0){
array[i][key] = value;
}
}
}
And then
setMultiple(array, "title", [0,1], "Manager");
Try this: `
for (var i=0; var<= array.length; i++){
array[i].title = "manager";
}`
Or you can change it around so var is less than or equal to any n range of keys in the index.
EDIT: instead make var <= 1. The point is to make for loops for the range of indices you want to change the title to.
Assuming that you have a bigger set of array objects.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
},
.
.
.
];
Create an object for the new keys you want to add like so:
let newKeys = {
'Manager': [0,2],
'Staff': [1]
}
Now you can add more such titles here with the required indexes.
with that, you can do something like:
function addCustomProperty(array, newKeys, newProp) {
for (let key in newKeys) {
array.forEach((el, index) => {
if (key.indexOf(index) > -1) { // if the array corresponding to
el[newProp] = key // the key has the current array object
} // index, then add the key to the
}) // object.
}
return array
}
let someVar = addCustomProperty(array, newKeys, 'title')

How to remove duplicate objects from JavaScript array

This is my code
var studentsList = [
{"Id": "101", "name": "siva"},
{"Id": "101", "name": "siva"},
{"Id": "102", "name": "hari"},
{"Id": "103", "name": "rajesh"},
{"Id": "103", "name": "rajesh"},
{"Id": "104", "name": "ramesh"},
];
function arrUnique(arr) {
var cleaned = [];
studentsList.forEach(function(itm) {
var unique = true;
cleaned.forEach(function(itm2) {
if (_.isEqual(itm, itm2)) unique = false;
});
if (unique) cleaned.push(itm);
});
return cleaned;
}
var uniqueStandards = arrUnique(studentsList);
document.body.innerHTML = '<pre>' + JSON.stringify(uniqueStandards, null, 4) + '</pre>';
OutPut
[
{
"Id": "101",
"name": "siva"
},
{
"Id": "102",
"name": "hari"
},
{
"Id": "103",
"name": "rajesh"
},
{
"Id": "104",
"name": "ramesh"
}
]
In the above code I got unique objects from the JavaScript array, but i want to remove duplicate objects. So I want to get without duplicate objects from the array, the output like
[
{
"Id": "102",
"name": "hari"
},
{
"Id": "104",
"name": "ramesh"
}
]
Check this
var uniqueStandards = UniqueArraybyId(studentsList ,"id");
function UniqueArraybyId(collection, keyname) {
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
This maybe? (not the most performant implementation but gets the job done):
var studentsList = [
{Id: "101", name: "siva"},
{Id: "101", name: "siva"},
{Id: "102", name: "hari"},
{Id: "103", name: "rajesh"},
{Id: "103", name: "rajesh"},
{Id: "104", name: "ramesh"},
];
var ids = {};
studentsList.forEach(function (student) {
ids[student.Id] = (ids[student.Id] || 0) + 1;
});
var output = [];
studentsList.forEach(function (student) {
if (ids[student.Id] === 1) output.push(student);
});
console.log(output);
Edit: faster method if the students are ordered by Id:
var studentsList = [
{Id: "101", name: "siva"},
{Id: "101", name: "siva"},
{Id: "102", name: "hari"},
{Id: "103", name: "rajesh"},
{Id: "103", name: "rajesh"},
{Id: "104", name: "ramesh"},
];
var output = [];
studentsList.reduce(function (isDup, student, index) {
var nextStudent = studentsList[index + 1];
if (nextStudent && student.Id === nextStudent.Id) {
return true;
} else if (isDup) {
return false;
} else {
output.push(student);
}
return false;
}, false);
console.log(output);
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
You can use javascript's filter method:
The solution for the above problem can be found in this fiddle.
The performance of this solution will be better because we are using pure javascript and there is no third party overhead.
app.controller('myCntrl',function($scope){
var seen = {};
//You can filter based on Id or Name based on the requirement
var uniqueStudents = studentsList.filter(function(item){
if(seen.hasOwnProperty(item.Id)){
return false;
}else{
seen[item.Id] = true;
return true;
}
});
$scope.students = uniqueStudents;
});
Let me know if you need any other details.
Here is the controller which will detect the duplicate element and remove it and will give you the element which has no duplicates. Just use this controller
$scope.names= studentsList.reduce(function(array, place) {
if (array.indexOf( studentsList.name) < 0)
array.push( studentsList.name );
else
array.splice(array.indexOf( studentsList.name), 1);
return array;
}, []);
Hope this works for your case
You can use library lodash and method uniqBy()
How about this one-liner function using Set()?
function arrUnique(arr) { return [...new Set(arr.map(JSON.stringify))].map(JSON.parse);}
It uses JSON.stringify() and JSON.parse() to transform the objects to string, because the equality function of Set() (===) is not customizable and doesn't work for objects, but for strings. JSON.parse() of the unique elements in the stringified version transforms them back to objects.
Very likely, this is not the fastest version because of overhead using JSON methods.
How about this, two different examples, the first gets all duplicates comparing a property rather than an Id or comparing the whole object. The second example is is a distinct list of duplicates.
// Sample 1 - Show all duplicates of a particular code rather than the whole record is unique
var sampleJson =
[
{ id: 1, code: "123-123" },
{ id: 2, code: "123-124" },
{ id: 3, code: "123-125" },
{ id: 4, code: "123-123" }
];
console.log("All duplicates");
let duplicates= [];
sampleJson.forEach(function (item) {
var checkForDuplicates = sampleJson.filter(a => a.code == item.code);
if (checkForDuplicates.length > 1) {
duplicates .push(item);
}
});
console.log(duplicates);
console.log( "Distinct duplicates");
// Sample 2 - Distinct list of duplicates
let distinctDuplicates= [];
sampleJson.forEach(function(item) {
var checkForDuplicates = sampleJson.filter(a => a.code == item.code);
if (checkForDuplicates.length > 1) {
// Ensure we only have the single duplicate by ensuring we do not add the same one twice
var exists = distinctDuplicates.filter(b => b.code == item.code).length == 1;
if (false === exists) {
distinctDuplicates.push(item);
}
}
});
console.log(distinctDuplicates);

searching a nested javascript object, getting an array of ancestors

I have a nested array like this:
array = [
{
"id": "67",
"sub": [
{
"id": "663",
},
{
"id": "435",
}
]
},
{
"id": "546",
"sub": [
{
"id": "23",
"sub": [
{
"id": "4",
}
]
},
{
"id": "71"
}
]
}
]
I need to find 1 nested object by its id and get all its parents, producing an array of ids.
find.array("71")
=> ["546", "71"]
find.array("4")
=> ["546", "23", "4"]
What's the cleanest way to do this? Thanks.
Recursively:
function find(array, id) {
if (typeof array != 'undefined') {
for (var i = 0; i < array.length; i++) {
if (array[i].id == id) return [id];
var a = find(array[i].sub, id);
if (a != null) {
a.unshift(array[i].id);
return a;
}
}
}
return null;
}
Usage:
var result = find(array, 4);
Demo: http://jsfiddle.net/Guffa/VBJqf/
Perhaps this - jsonselect.org.
EDIT: I've just had a play with JSONSelect and I don't think it's appropriate for your needs, as JSON does not have an intrinsic 'parent' property like xml.
It can find the object with the matching id, but you can't navigate upwards from that. E.g.
JSONSelect.match(':has(:root > .id:val("4"))', array)
returns me:
[Object { id="4"}]
which is good, it's just that I can't go anywhere from there!

Categories