Parse a Javascript Object into an array [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
Okay, so I have a Javascript object that I printout to the console into the following form:
(3) [{…}, {…}, {…}]
0: {data: 50, label: "Active Users"}
1: {data: 20, label: "Expired Users"}
2: {data: 30, label: "Renewed Users"}
length: 3
__proto__: Array(0)
I am trying to extract out the data and label values into separate arrays.
This is what I have done:
var dataObject = doughnutdata;
var obj = JSON.parse(JSON.stringify(dataObject));
console.log(obj);
var labelsdata = [];
var datadummy = [];
labelsdata.push(obj.label);
datadummy.push(obj.data);
console.log(labelsdata);
console.log(datadummy);
But I get [undefined] for both labelsdata and datadummy.
On a sidenote, this is how I have set my doughnutdata:
var doughnutdata = #Html.Raw(Json.Encode(Model.dummysubscribeddata));
Can anyone help me out with this problem?
Thanks.

Try simple loop.
let values = [
{data: 50, label: "Active Users"},
{data: 50, label: "Active Users"},
{data: 50, label: "Active Users"},
{data: 50, label: "Active Users"},
];
let data = [];
let label = [];
for(const value of values) {
data.push(value.data);
label.push(value.label);
}
console.log('data: ', data);
console.log('label: ', label);

Related

findIndex of item in array of object where object property match [duplicate]

This question already has answers here:
findIndex() javascript array object
(2 answers)
How do I get the index of object in array using angular?
(5 answers)
Get objects position in array
(3 answers)
Closed 1 year ago.
I have an array of object as follow :
[ {label: "<p>Opacity | %<br/></p>", customRow: false, id: 0, items: Array(13)},
{label: "Brand_hs_id", customRow: false, id: 0, items: Array(13)},
{label: "<p>PPI |</p>", customRow: false, id: 0, items: Array(13)},
{label: "Brightness | %", customRow: false, id: 0, items: Array(13)
]
I want to findIndex of object where label value matches. for example if I pass the "Brightness | %" it should return 3.
I checked
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
but not sure how to do it in array of objects .
Try something like as follows:
let val = [{id:"1002", address:"usa"},
{id:"1004", address:"canada"},
{id:"1006", address:"sweden"}];
let index = val.findIndex(x => x.address === "canada");
console.log(index); //Here index will be returned
do it like this
const array1 = [{age:5}, {age:12},{age:8} , {age:130}, {age:44}];
const isLargeNumber = (element) => element.age > 13;
console.log(array1.findIndex(isLargeNumber));

How to pass data to a JSON array in nodejs?

i want to pass data from one JSON array to another. My first json array is below:
var data = [{"Commodity":"Apparel and clothing accessories; knitted or crocheted"},{"Commodity":"Fish and crustaceans, molluscs and other aquatic invertebrates"},{"Commodity":"Meat, fish or crustaceans, molluscs or other aquatic invertebrates; preparations thereof"},{"Commodity":"Natural, cultured pearls; precious, semi-precious stones; precious metals, metals clad with precious metal, and articles thereof; imitation jewellery; coin"},{"Commodity":"Sugars and sugar confectionery"}];
I want to pass each of the "Commodity" values to my second JSON array. I tried using a for loop:
var arr = [];
for(let j = 0; j < data.length; j++) {
arr = [{"title":"Select a commodity:","options":[{"label":data[j]['Commodity'],"value":{"input":{"text":data[j]['Commodity']}}}],"description":"","response_type":"option"}];
}
I need each of the "Commodity" values to be filled inside the "label" and "text" property. However on output, only the last "Commodity" - "Sugars and sugar confectionery" is being displayed in the arr.
Any idea would help. Thank you.
UPDATES:
This is how the output looks like but the "Select a commodity" should only be printed out once. This is a response type option from ibm watson assistant.
EDIT :
let arr = {
title: "Select a commodity:",
response_type: "option",
description: "",
options:data.map(element => {
return {
label: element.Commodity,
value: {text: element.Commodity}
}
})
}
console.log(arr);
OUTPUT
{
response_type: "option"
title: "Select a commodity:"
description: ""
options: Array(5)
0: {label: "Apparel and clothing accessories; knitted or crocheted", value: {…}}
1: {label: "Fish and crustaceans, molluscs and other aquatic invertebrates", value: {…}}
2: {label: "Meat, fish or crustaceans, molluscs or other aquatic invertebrates; preparations thereof", value: {…}}
3: {label: "Natural, cultured pearls; precious, semi-precious …, and articles thereof; imitation jewellery; coin", value: {…}}
4: {label: "Sugars and sugar confectionery", value: {…}}
}
The problem is you're actually using the "=" operator, which is re-assigning the value to your array - arr.
Instead of arr = [{...
Try using:
var arr = [];
for(let j = 0; j < data.length; j++) {
arr.push({"title":"Select a commodity:","options":[{"label":data[j]['Commodity'],"value":{"input":{"text":data[j]['Commodity']}}}],"description":"","response_type":"option"});
}

Loop through json object to get values of particular key [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
0: {id: "7B5B201E-35AA-48A1-B919-002445319F8B", name: "Naman Sabarwal"}
1: {id: "EA6672BA-4F7A-4214-A37F-00716CE698C9", name: "me name"}
2: {id: "01F29920-9206-42DF-8151-00A6A080C501", name: "Nitesh Negi"}
I want to get a list such that the list contains only the name key values.
listOfNames = ['sonu singh','me name','harman jain']
How to get all the values of the key 'name'?
listOfNames = jsonValues.map(x=>x.name)
You can try as follow.
let data = [
{id: "7B5B201E-35AA-48A1-B919-002445319F8B", name: "Naman Sabarwal"},
{id: "EA6672BA-4F7A-4214-A37F-00716CE698C9", name: "me name"},
{id: "01F29920-9206-42DF-8151-00A6A080C501", name: "Nitesh Negi"}
]; // assume the data is in array
let result = data.map( d => d.name );
console.log(result);
if it is json object like
details = [{id:"",name:""},{id:"",name:""},{id:"",name:""}]
you can use map function like
function getnames(){
let names = []
details.map((detail)=>{
names.push({name:detail.name})
return names
}
to shorten this
let names = values.map(value=>return value.name)

Combining Array of Objects with another Object of Arrays After Component Mounts in React

I'm using eBay Api to update values for items i have stored in a database.
On my Favorites page, i'm displaying a user's favorite items.
I have the user's saved favorites which are loaded when the component mounts. The favorites data is an array of objects and looks like this:
{id: Array(1), title: Array(1), image: Array(1), itemURL: Array(1), price: 64, …}
{id: Array(1), title: Array(1), image: Array(1), itemURL: Array(1), price: 24, …}
{id: Array(1), title: Array(1), image: Array(1), itemURL: Array(1), price: 8, …}
{id: Array(1), title: Array(1), image: Array(1), itemURL: Array(1), price: 392, …}
{id: Array(1), title: Array(1), image: Array(1), itemURL: Array(1), price: 1501, …}
Based on the id's from the favorites array above, i'm sending an API call to generate updated data for the statically saved variables such as bids, price etc. This data is saved in an object called cards..here is an example of data format:
cards: "[{"id":"143204954724","title":"1939-46 Salutation Exhibit,Hubbell,NY Giants,SGC70,HOF","price":64.99,"bidCount":0,"status":"Active","timeLeft":"P24DT9H1S"},
I need to create a combined array on page load while also updating whenever the page is refreshed or updated--that matches up ID's from both arrays.
For example, if an item from favorites array contains the ID 344, I need to match that to the cards object and replace the data in favorites with data from cards object.
So if a favorite item looks like this:
{id: 344, link: google.com, title: "Awesome Sauce", price: 64, bids: 30}
and the same item in cards looks like this:
{id: 344, bids: 34, price: 75}
then i need the two to converge to an updated item like so:
{id: 344, link: google.com, title: "Awesome Sauce", price: 75, bids: 34}
Should I map through the favorites array and match to the cards object and just insert the new values? While also creating a hook to call this mapping? I sort of think that's what I need to do, but I'm not exactly sure where to start.
UPDATE--this is what i'm trying
const combineData = (favorites, favUpdates) => {
const finalArray = [];
const data = Array.from(favorites);
console.log("DATA", favorites);
data.forEach(item1 =>
favUpdates.forEach(item2 => {
if (item1.id === item2.id)
finalArray.push(item2, item1.image, item1.itemURL);
})
);
console.log("Final Array", finalArray);
};
I added an additional effect hook like this but when i console log finalArray it's empty. I think it must be that the data its using isn't loaded yet (i think?)
const Favorites = props => {
useEffect(() => {
props.getFavorites(props.loggedUser.id);
}, [props.loggedUser.id]);
useEffect(() => {
setData(props.cardsToShow);
}, [props]);
const mapFAVS = props.favorites;
const data = Array.from(mapFAVS);
const updatedFavs = data.map(item => item.id);
const formatFavs = updatedFavs.map(id => id.join(","));
useEffect(() => {
props.getUpdates(formatFavs);
}, [props.favorites]);
useEffect(() => {
combineData(props.favorites, props.favUpdates);
}, []);
You could do something like....
let array = [{currentObjects}];
//some promise {
array = [...array, additionalObjects];
// }
have you tried concat javascript?
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
// creates array ["a", "b", "c", 1, 2, 3]; alpha and numeric are unchanged
var alphaNumeric = alpha.concat(numeric);

Javascript: Add array elements to another array

I need to split elements in array noted below into 2 separate arrays:
data and labels:
Example using below would look like this:
data: [9, 23, 1, 6]
labels: ['service-1', 'service-2', 'service-3', 'service-4']
Array[16]
. 0: Object
. data: 9
. labels: "service-1"
. __proto__: Object
. 1: Object
. data: 23
. labels: "service-2"
. __proto__: Object
. 2: Object
. data: 1
. labels: "service-3"
. __proto__: Object
. 3: Object
. data: 6
. labels: "service-4"
. __proto__: Object
I'm trying to keep this simple as possible as I've tried several different things that have not worked including reference in this post: add array elements to other,
Try this:
var dataLabels = [
{data: 9, label: "service-1"},
{data: 23, label: "service-2"},
{data: 1, label: "service-3"},
{data: 6, label: "service-4"}
];
var data = [];
var labels = [];
dataLabels.forEach(function(element) {
data.push(element.data);
labels.push(element.label);
});
Assuming your array has a JS object notation, I think this should work:
var data = [];
var labels = [];
for (var i= 0;i<16; i++){
data[i] = array[i].data;
labels[i] = array[i].labels;
}
This should do the trick. Although perhaps a loop will suffice.
var dataLabels = [
{
data: 9,
labels: "service-1"
}, {
data: 23,
labels: "service-2"
}
];
var data = dataLabels.map(function(element) {
return element.data;
});
var labels = dataLabels.map(function(element) {
return element.labels;
});

Categories