Push object to a JSON file subarray/object - javascript

Both JS or Node.js solution are welcome
I have a json file with following structure (I have remove some unnecessary part)
{
"post": {
"sample_post": {
"slug": "/sample"
}
}
}
And I want to push a new object array like "sample_post" and someone suggest to change this array to
{
"post": [{
"sample_post": {
"slug": "/sample"
}
}]
}
to use push but I got error like data.push is not a function since I use jquery to get the external json I don't know if this cause error

based on your code :
var data = {
"post": {
"sample_post": {
"slug": "/sample"
}
}
}
you have to use a temporary variable to store the new array :
var _tmp = []
_tmp.push(data.post)
and overright your initial data
data.post = _tmp

I m not sure what you want is just :
var test = {
"post": {
"sample_post": {
"slug": "/sample"
}
}
};
test.post = [test.post];

If you prepare object like shown below,
var obj = {
"post": [{
"sample_post": {
"slug": "/sample"
}
}]
}
then you should be adding the objects into "post" array, in either of the ways.
obj.post.push({"key": "value"})
or
obj["post"].push({"key": "value"})

To use push function, the object should be of type Array. But in your case its a json object. So you first need to make it Array either by initializing it by blank array. ie data.post = [] or directly with array with required elements. After this you can use push in post.push().
Hope this help!

Related

Access and extract values from doubly nested array of objects in JavaScript

I have an array of objects and within those objects is another object which contains a particular property which I want to get the value from and store in a separate array.
How do I access and store the value from the name property from the data structure below:
pokemon:Object
abilities:Array[2]
0:Object
ability:Object
name:"blaze"
1:Object
ability:Object
name:"solar-power"
How would I return and display the values in the name property as a nice string like
blaze, solar-power ?
I tried doing something like this but I still get an array and I don't want to do a 3rd loop since that is not performant.
let pokemonAbilities = [];
let test = pokemon.abilities.map((poke) =>
Object.fromEntries(
Object.entries(poke).map(([a, b]) => [a, Object.values(b)[0]])
)
);
test.map((t) => pokemonAbilities.push(t.ability));
Sample Data:
"pokemon": {
"abilities": [
{
"ability": {
"name": "friend-guard",
"url": "https://pokeapi.co/api/v2/ability/132/"
},
"ability": {
"name": "Solar-flare",
"url": "https://pokeapi.co/api/v2/ability/132/"
}
}
]
}
Then I am doing a join on the returned array from above to get a formatted string.
It just seems like the multiple map() loops can be optimized but I am unsure how to make it more efficient.
Thank you.
There is no need for a loop within loop. Try this:
const pokemon = {
abilities: [{
ability: {
name: 'friend-guard',
url: 'https://pokeapi.co/api/v2/ability/132/'
},
}, {
ability: {
name: 'Solar-flare',
url: 'https://pokeapi.co/api/v2/ability/132/'
}
}]
};
const pokemonAbilities = pokemon.abilities.map(item => item.ability.name).join(', ');
console.log(pokemonAbilities);

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Getting values of json array in Mocha JS

I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)

Extract data from API Object in React

I'm trying to retrieve data from an API with the following JSON output and I have a function in react that I call.
I can see the api output in console.log(users) so the data is being passed into the function.
I am trying to output the array contained in "data" but can't seem to access the data.
{
"dataCount": 2,
"data": [
{
"name": "Test review header",
"text": "This is adescription for a test review",
"img": "http://pngimg.com/upload/pigeon_PNG3423.png"
},
{
"name": "Test review header2",
"text": "This is adescription for a test review2",
"img": "http://pngimg.com/upload/pigeon_PNG3422.png"
}
]
}
renderUsers() {
const { users } = this.props;
console.log(users);
Object.keys(users).map(name => users[name])
console.log(users[name]);
};
The data you need to iterate over is present in the data field of users.
When you are using lists you have to specify the key property, to make react keep track of each item in list.
renderUsers() {
const { users } = this.props;
return (
<ul>
{
users.data.map(name => {
<li key={name}>users[name]</li>
})
}
</ul>
)
}
First of all, I don't use react but what you want should be the same in other javascript frameworks.
Are you sure that it is JSON you receive?
We need to be sure that you receive a JSON object and not normal text. Lets say you have a function parseResponse(data). We can call JSON.parse(data) to parse the data param to a json object. It is also possible that you store the result in a variable.
Using the JSON object
When we are sure you have the param parsed to a JSON object, we get it's data. For example, if you want to get the name of the first object in data, you can call:
parsedJson.data[0].name
where parsedJson is the result of JSON.parse(data),
data is an array of objects in the JSON,
0 is the first object in the array
It is possible that you have this kind of function then:
function parseResponse(data) {
var parsedJson = JSON.parse(data);
for(var i = 0; i < parsedJson.data.length; i++) {
console.log(parsedJson.data[i].name);
}
}
see jsfiddle

How can i build this json format in javascript?

I have this json where the values will be passed dynamically in javascript,
{
"User": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"memNum": "70000211981",
"orderslist": [
{
"orderid": "5119534",
"ordersource": "ONLINE",
"transactiondttm": "2014-01-09"
},
{
"orderid": "5119534",
"ordersource": "STORE",
"transactiondttm": "2014-01-09"
}
]
}
}
and i tried using this function to build the json but it doesnt seem to work,
function addOrder(req, orderId, orderSource, transactiondtm) {
req.User.orderslist.orderid.push(orderId);
req.User.orderslist.ordersource.push(orderSource);
req.User.orderslist.transactiondtm.push(transactiondtm);
}
Any suggestion..
The elements of orderslist are objects, not arrays, so you can't push onto them. You have to build them as objects, and then push that onto the orderslist array.
function addOrder(req, orderId, orderSource, transactiondtm) {
req.User.orderslist.push({ orderid: orderId,
ordersource: orderSource,
transactiondtm: transactiondtm });
}
Something like this should work.
function addOrder(req, orderId, orderSource, transactiondtm) {
req.User.orderslist.push({
"orderid": orderId,
"ordersource": orderSource,
"transactiondtm": transactiondtm
});
}
Javascript objects can be acessed like an array.
That way you can create dinamic members.
user = {"orderList":[]};
for(var i = 0; i<5; i++){
user.orderList[i] = {};
user.orderList[i]["orderId"] = i;
user.orderList[i]["orderSource"] = "STORE";
}
alert(user.orderList[0].orderSource);
//Shows "STORE"
you can see the code working here http://jsfiddle.net/wmgE6/

Categories

Resources