Reading only the first value in JavaScript - javascript

I am trying to add the below body to JSON. But I only see one value is being added.
json = { "Myname":"Nate", }
Adding the below code:
Body = Myproperty: [{
"vehicle": "car",
"color": "Red"
}, {
"name": "van",
"color": "white"
}, {
"name": "Truck",
"color": "Blue"
}]
Here is the code I am using:
for (var i = 0; i < Myproperty.length; i++) {
json.mycarname = Body.Myproperty[i].name;
json.mycolor = Body.Myproperty[i].color;
}
The end result should look like this:
{
"Myname": "Nate",
mycarname: "car",
"mycolor": "Red"
},
{
"Myname": "Nate",
mycarname: "van",
"mycolor": "white"
},
{
"Myname": "Nate",
mycarname: "Truck",
"mycolor": "Blue"
}

I guess you want to do something like this:
var myName = "Nate";
var Body = [{
"name": "car",
"color": "Red"
},
{
"name": "van",
"color": "white"
},
{
"name": "Truck",
"color": "Blue"
}
]
var json = [];
for (var i = 0; i < Body.length; i++) {
json.push({
"Myname": myName,
"mycarname": Body[i].name,
"mycolor": Body[i].color
});
}
console.log(json)
The idea is to loop over the entries you want to add and push them into the json array.

Related

Array item using its own parent object index as its value?

lets say we have :
let array_of_objects = [
{
"color": "purple",
"type": "minivan",
"id": this.object.index // i know this is not valid code,but can this somehow get its own index within the array as value ?
},
{
"color": "red",
"type": "station wagon",
"id": this.object.index //this should be 1
}
]
Actual question in code comments..
what i'm trying to do is to fill a form's inputs using an object,and i want to be able to display the actual index of the object within the array in one of the inputs
instead of using index as id I suggest create a complex id or you can use uuid() library for creating unique user id uuid npm
import { v4 as uuidv4 } from 'uuid';
array_of_objects = array_of_objects.map((item, index) => ({ id: uuidv4(), ...item}))
console.log(array_of_objects);
let array_of_objects = [
{
"color": "purple",
"type": "minivan"
},
{
"color": "red",
"type": "station wagon"
}
];
array_of_objects = array_of_objects.map((item, index) => ({ id: index, ...item}))
console.log(array_of_objects);
Just initialize the array without the id and add it afterwards using a for loop.
let array_of_objects = [
{
"color": "purple",
"type": "minivan",
},
{
"color": "red",
"type": "station wagon",
}
]
for (let i = 0; i < array_of_objects.length; i++) {
array_of_objects[i].id = i;
}
You can use Object.keys(arrayVarible) to get the indexes of array which outputs as an array as well.
let array_of_objects = [
{
"color": "purple",
"type": "minivan",
},
{
"color": "red",
"type": "station wagon",
}
];
console.log(Object.keys(array_of_objects))
Each time the the array changes or you fill the form run this code
console.log(array_of_objects.length-1)

how to push array value to another array object value javascript

I've data response like this
{
"data": {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [
{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
}
}
and then i want push the colors inside items
expected: items have three(3) variable each of index
items: [
{
label: phone,
value: 23.00,
color: #3498db
}
]
i've try using push and concat but i got error "Cannot read property 'data' of undefined"
here my code
generaliseData(dashboardC) {
let genData = Object.assign({}, dashboardC)
if (genData.product.items.length > 0) {
for (let i of genData.product.items) {
i.value = parseInt(i.value)
for (let j of genData.product.colors) {
i = i.push(j)
}
}
console.log(genData)
}
}
You can use map to iterate through your list, expect to have the length of colors equal the length of item
const response = {
"data": {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [
{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
}
};
function addColorToItem(response) {
const product = response.data.product;
const colors = product.colors;
const items = product.items;
return items.map((item, index) => {
item.color = colors[index];
return item;
})
}
console.log(addColorToItem(response));
You could iterate items and assign a color.
var response = { data: { product: { colors: ["#3498db", "#00ccff"], items: [{ label: "Phone", value: "23.00" }, { label: "Notebook", value: "3.00" }] } } },
temp = response.data.product;
temp.items.forEach((o, i) => o.color = temp.colors[i]);
console.log(response);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use a simple forEach() loop for that result:
var data = {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
};
data.product.items.forEach((item, index) => item.color = data.product.colors[index]);
console.log(data);

How to assign values of one array to another array?

I have got two arrays by name actutalpricesarray and modfiedpricesarray .
var actutalpricesarray =
[
{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
]
var modfiedpricesarray =
[
{"name":"apple","price":20},
{"name":"orange","price":30},
{"name":"strawberry","price":40}
]
I want to assign price values modfiedpricesarray to actutalpricesarray , so that the output of modfiedpricesarray will look like
[{"name":"apple","price":100},{"name":"orange","price":200},{"name":"strawberry","price":40}]
tried it this way
for(var i=0;i<modfiedpricesarray.length;i++)
{
var fruitnamemodfiedprice = modfiedpricesarray[i].name;
for(var j=0;j<actutalpricesarray.length;j++)
{
var fruitnameactualprice = actutalpricesarray[j];
if(fruitnamemodfiedprice==fruitnameactualprice)
modfiedpricesarray[i].price = actutalpricesarray[j].price;
}
}
console.log(JSON.stringify(modfiedpricesarray))
});
https://jsfiddle.net/o2gxgz9r/55230/
desired output of modfiedpricesarray should be
[
{"name":"apple","price":100},
{"name":"orange","price":200},
{"name":"strawberry","price":40}
]
Hey here is what you can do. I used the findIndex to get the index of the desired fruit then I update the price. Check my codepen too
var actutalpricesarray =[
{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
]
var modfiedpricesarray = [
{"name":"apple","price":20},
{"name":"orange","price":30},
{"name":"strawberry","price":40}
]
modfiedpricesarray.forEach((item,i) => {
var fruitnamemodfiedprice = item.name;
let index = actutalpricesarray.findIndex(x => x.name === fruitnamemodfiedprice);
if(index !== -1){
modfiedpricesarray[i].price = actutalpricesarray[index].price
}
})
console.log(JSON.stringify(modfiedpricesarray))
You can directly filter the array and then update value accordingly. You can test it below.
var actutalpricesarray = [{
"name": "apple",
"price": 100
},
{
"name": "orange",
"price": 200
}
];
var modfiedpricesarray = [{
"name": "apple",
"price": 20
},
{
"name": "orange",
"price": 30
},
{
"name": "strawberry",
"price": 40
}
]
actutalpricesarray.forEach((data) => {
modfiedpricesarray.filter((d) => d.name == data.name).forEach((d) => d.price = data.price);
});
console.log(modfiedpricesarray);

Group and count values in an array

I have an array with objects, like the following.
b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.
a = [
{Name: 'Backlog', count: 1},
{Name: 'close', count: 2}
];
I have tried the following.
b.issues.forEach(function(i) {
var statusName = i.fields.status.name;
if (statusName in a.Name) {
a.count = +1;
} else {
a.push({
Name: statusName,
count: 1
});
}
});
That however doesn't seem to be working. How should I implement this?
This is a perfect opportunity to use Array#reduce. That function will take a function that is applied to all elements of the array in order and can be used to accumulate a value. We can use it to accumulate an object with the various counts in it.
To make things easy, we track the counts in an object as simply {name: count, otherName: otherCount}. For every element, we check if we already have an entry for name. If not, create one with count 0. Otherwise, increment the count. After the reduce, we can map the array of keys, stored as keys of the object, to be in the format described in the question. See below.
var b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
var counts = b.issues.reduce((p, c) => {
var name = c.fields.status.name;
if (!p.hasOwnProperty(name)) {
p[name] = 0;
}
p[name]++;
return p;
}, {});
console.log(counts);
var countsExtended = Object.keys(counts).map(k => {
return {name: k, count: counts[k]}; });
console.log(countsExtended);
.as-console-wrapper {
max-height: 100% !important;
}
Notes.
Array#reduce does not modify the original array.
You can easily modify the function passed to reduce to for example not distinguish between Backlog and backlog by changing
var name = c.fields.status.name;
into
var name = c.fields.status.name.toLowerCase();
for example. More advanced functionality can also easily be implemented.
Using ES6 Arrow functions you can do it with minimum syntax
var b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
var countOfBackLog = b.issues.filter(x => {
return x.fields.status.name === "Backlog"
}).length
var countOfClose = b.issues.filter(x => {
return x.fields.status.name === "close"
}).length
a =[{Name: 'Backlog', count : countOfBackLog}, {Name: 'close', count : countOfClose}]
More about arrow functions here
You can write like this. It is dynamic.
var a = {};
for(var key in b["issues"]){
if(!a.hasOwnProperty(b["issues"][key].fields.status.name)){
a[b["issues"][key].fields.status.name] = 1;
}else{
a[b["issues"][key].fields.status.name] = a[b["issues"][key].fields.status.name]+1;
}
}
var c = [];
for(var key1 in a){
c.push({
name : key1,
count : a[key1]
});
}
Something like this should do the trick. Simply iterate over your data, keep 2 counters with the number of each type of issue, and create the data format you want in the end. Try it live on jsfiddle.
var b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
var data = [];
for(var issue of b.issues){
var entryFound = false;
var tempObj = {
name: issue.fields.status.name,
count: 1
};
for(var item of data){
if(item.name === tempObj.name){
item.count++;
entryFound = true;
break;
}
}
if(!entryFound){
data.push(tempObj);
}
}
console.log(data);

creating json using javascript

I want to create a json using object & javascript. the function object_merge is used to merge the object values.
here is the code i'm using.
var dat0 = [{
"type": "configuration",
"Process": [{
"type": "Source",
"value": ticket_id
}],
"attributes": {
}
}];
function object_merge(){
for (var i=1; i<arguments.length; i++)
for (var a in arguments[i])
arguments[0][a] = arguments[i][a];
return arguments[0];
};
var arry = [];
var listobj= [object0,object1,object2,object3,object4,object5,object6,object7,object8,object9];
var object1 = {TicketID: [{value: ticket_id }]};
var object2 = {Score:[{value: ticket_score }]};
var object3 = {Requestor:[{value: ticket_requestor_name }]};
var object4 = {Submitter:[{value: ticket_submitter_name }]};
var object5 = {Channel:[{value: ticket_channel }]};
var object6 = {Priority:[{value: ticket_priority }]};
var object7 = {Status:[{value: ticket_status }]};
var object8 = {Subject:[{value: ticket_subject }]};
var object9 = {Group:[{value: ticket_group_name }]};
var object0 = {TicketType:[{value: ticket_type }]};
if ((object1.TicketID[0].value!== (null)||(undefined)))
{
arry.push(object1);
}
if (object2.Score[0].value!== (null)||(undefined))
{
arry.push(object2);
}
if (object3.Requestor[0].value!== (null)||(undefined))
{
arry.push(object3);
}
if (object4.Submitter[0].value!== (null)||(undefined))
{
arry.push(object4);
}
if (object5.Channel[0].value!== (null)||(undefined))
{
arry.push(object5);
}
if (object6.Priority[0].value!== (null)||(undefined))
{
arry.push(object6);
}
if (object7.Status[0].value!== (null)||(undefined))
{
arry.push(object7);
}
if (object8.Subject[0].value!== (null)||(undefined))
{
arry.push(object8);
}
if (object9.Group[0].value!== (null)||(undefined))
{
arry.push(object9);
}
if (object0.TicketType[0].value!== (null)||(undefined))
{
arry.push(object0);
}
var attr = object_merge(arry);
console.info(JSON.stringify(attr));
dat0[0].attributes = attr;
console.info(JSON.stringify(dat0));
which returns a json like
[{"type":"configuration","Process":[{"type":"Source","value":902}],"attributes":[{"TicketID":[{"value":902}]},{"Score":[{"value":"unoffered"}]},{"Requestor":[{"value":"raj"}]},{"Submitter":[{"value":"raj"}]},{"Channel":[{"value":"api"}]},{"Status":[{"value":"open"}]},{"Subject":[{"value":"sub"}]},{"Group":[{"value":"Support"}]}]}]
where as the expected result is
[{"type":"configuration","Process":[{"type":"Source","value":"902"}],"attributes":{"TicketID":[{"value":"902"}],"Score":[{"value":"unoffered"}],"Requestor":[{"value":"raj"}],"Submitter":[{"value":"raj"}],"Channel":[{"value":"api"}],"Status":[{"value":"open"}],"Subject":[{"value":"sub"}],"Group":[{"value":"Support"}]}}]
How to achieve it?
Try below code which may help you.
var attributesObject = {
"TicketID": [{
"value": "902"
}],
"Score": [{
"value": "unoffered"
}],
"Requestor": [{
"value": "raj"
}],
"Submitter": [{
"value": "raj"
}],
"Channel": [{
"value": "api"
}],
"Status": [{
"value": "open"
}],
"Subject": [{
"value": "sub"
}],
"Group": [{
"value": "Support"
}]
};
var main = [{
"type": "configuration",
"Process": [{
"type": "Source",
"value": "ticket_id"
}],
"attributes": attributesObject
}];
use this function instead of your object_merge:
function object_merge(objects) {
var newObject = {};
for (var i = 0; i < objects.length; i++)
for (var key in objects[i])
newObject[key] = objects[i][key];
return newObject;
};

Categories

Resources