how to convert json map to array ? Angular - javascript

I have the json like follow example, i would like to convert this json map to array for to be able to loop on it.
I use the Object.keys method but I don't know how to have a key => value format for the whole json.
I need to get the keys to make a table I know there is the pipe keyvalue but it's not what I need. or maybe I use it wrong
example json
{
"pays": "UK"
"test": [
[
"123456", // here i want key id
"blabla", // here i want key name
"lorem ipsum" // here i want key type
],
[
"654321",
"ipsum",
"blabla"
]
]
}
components.ts
get() {
this.myService.getUrl().subscribe(data => {
this.myArray = Object.keys(data).map((key) => {
return {
id: key,
name: data[key]
}
}):
}

Please try this
var input: any = {
"pays": "UK",
"test": [
[
"123456", // here i want key id
"blabla", // here i want key name
"lorem ipsum" // here i want key type
],
[
"654321",
"ipsum",
"blabla"
]
]
}
input .test = input.test.map((item: any) => {
return {
id: item[0],
name : item[1],
type : item[2]
}
})

This is one possible solution to transform array of strings into array of JSONs:
let input = {
pays: "UK",
test: [
[
"123456",
"blabla",
"lorem ipsum"
],
[
"654321",
"ipsum",
"blabla"
]
]
};
let result = {};
result.pays = input.pays;
result.test = [];
for (let i = 0; i < input.test.length; i++){
let testEl = input.test[i];
let resultObj = {};
resultObj.id = testEl[0];
resultObj.name = testEl[1];
resultObj.type = testEl[2];
result.test.push(resultObj);
}
console.log(result)

Related

Change value of key at different level in json using node js/ javascript

I am trying to replace a specific value from the JSON file. let's suppose given below is my JSON data
sample.json
let sample={
"yuiwedw":{
"id":"yuiwedw",
"loc": "ar",
"body":{
"data":"we got this",
"loc":"ar",
"system":{
"fname":"admin",
"lname":"admin",
"details":[
{
"id":"Admin_01",
"loc":"ar"
},
{
"id":"Admin_02",
"loc":"ar"
}
]
}
}
},
"hbjds324":{
"id":"hbjds324",
"loc": "ar",
"body":{
"data":"testing",
"loc":"ar",
"system":{
"fname":"public",
"lname":"servent",
"details":[
{
"id":"public_01",
"loc":"ar"
}
],
"Available":true,
"loc":"ar"
}
}
}
}
for (const value of Object.values(
sample )) {
value.loc = "en";
}
console.log(sample);
So I want to replace all the loc values which is ar with the en I can replace the value which at the first level but how to change all the loc value which is present at a different level.
You could write a simple recursive function to handle this.
This iterates over keys and if the value of a key is an object it calls itself.
If the key is loc it replaces it value.
Here's jsfiddle with your sample.
Example:
function replaceLoc(obj){
for(const key of Object.keys(obj)){
if (typeof obj[key] === 'object'){
replaceLoc(obj[key]);
}
if (key === 'loc'){
obj[key] = 'en'
}
}
}
replaceLoc(sample);
let sample={
"yuiwedw":{
"id":"yuiwedw",
"loc": "ar",
"body":{
"data":"we got this",
"loc":"ar",
"system":{
"fname":"admin",
"lname":"admin",
"details":[
{
"id":"Admin_01",
"loc":"ar"
},
{
"id":"Admin_02",
"loc":"ar"
}
]
}
}
},
"hbjds324":{
"id":"hbjds324",
"loc": "ar",
"body":{
"data":"testing",
"loc":"ar",
"system":{
"fname":"public",
"lname":"servent",
"details":[
{
"id":"public_01",
"loc":"ar"
}
],
"Available":true,
"loc":"ar"
}
}
}
}
function replaceLoc(obj){
for(const key of Object.keys(obj)){
if (typeof obj[key] === 'object'){
replaceLoc(obj[key]);
}
if (key === 'loc'){
obj[key] = 'en'
}
}
}
replaceLoc(sample);
console.log(sample);
To search and replace nested values you can use recursion (Make your for... into a function and call the function from within itself on all nested objects). Edit: the other answer shows how to do this.
You could also do it using regex. Example:
const regex = /"loc": *"ar"/g
const updatedSample = JSON.stringify(sample).replace(reg, `"loc":"ar"`);
Explanation: the regex finds "loc":"ar" with 0 to infinite spaces after the :. The JavaScript then replaces those with the value you give it. Here is an example showing how it works.
Alternatively,
You can convert a JSON object into a string, and replace all occurrences with regex and convert them back to JSON
const sampleString = JSON.stringify(sample);
const updatedSample = sampleString.replace(/"loc":"ar"/g, `"loc":"en"`);
const newSample = JSON.parse(updatedSample);
console.log(newSample);
Complete Example Below:
let sample = {
yuiwedw: {
id: "yuiwedw",
loc: "ar",
body: {
data: "we got this",
loc: "ar",
system: {
fname: "admin",
lname: "admin",
details: [
{
id: "Admin_01",
loc: "ar"
},
{
id: "Admin_02",
loc: "ar"
}
]
}
}
},
hbjds324: {
id: "hbjds324",
loc: "ar",
body: {
data: "testing",
loc: "ar",
system: {
fname: "public",
lname: "servent",
details: [
{
id: "public_01",
loc: "ar"
}
],
Available: true,
loc: "ar"
}
}
}
};
const sampleString = JSON.stringify(sample);
const updatedSample = sampleString.replace(/"loc":"ar"/g, `"loc":"en"`);
const newSample = JSON.parse(updatedSample);
console.log(newSample);

How to write forEach function for JSON data in javascript

I want to write a forEach function for finding out data in my JSON
Case:
[[{ {"Plan-Name = "qwe" , "plan_data" = "10"}
{"Plan-Name = "asd" , "plan_data" = "10"}
{"Plan-Name = "wrt" , "plan_data" = "10"}
}]]
I want to search wrt and print its plan_data
and I have a Current plan = wrt, so if the current plan matches with Plan_name then print its Plan_data
I for my current plan responseJson[0][0]['cuurent_plan']
and for Plan_name responseJson[2]
It seems the JSON is invalid, if it's a valid JSON then you can do as below for your desired result.
const getPlanData = (planData, planName: string) => {
const planInfo = planData.find((plan) => plan["Plan-Name"] === planName);
return planInfo;
}
const apIResponse = [[
{ "Plan-Name": "qwe", "plan_data": "11" },
{ "Plan-Name": "asd", "plan_data": "22" },
{ "Plan-Name": "wrt", "plan_data": "33" }
]
]
const planValue = getPlanData(apIResponse[0], 'wrt')
console.log('res', planValue);

Change particular key in nested array to object in javascript

If the fields key in a object is array, change the first value of arrays as a key value pair object in javascript.
var obj =
[
{ id:1, fields:["item", "2", "list"]},
{ id:2, fields:["sample", "1", "check"]}
]
function newObj(obj) {
let objFields = {};
modifiedObj.fields.forEach(field => objFields[field] = field);
modifiedObj.fields= objFields;
return modifiedObj;
}
var result = this.newObject(obj)
Expected Output
{
item: "item",
sample: "sample"
}
Try this:
var obj =
[
{ id:1, fields:["item", "2", "list"]},
{ id:2, fields:["sample", "1", "check"]}
]
function newObject(obj) {
let objFields = {};
obj.forEach(e => {
if(e.fields && e.fields.length>0)
objFields[e.fields[0]] = e.fields[0];
});
return objFields;
}
var result = this.newObject(obj);
console.log(result);
Here is a functional approach that makes use of Object.assign(), spread operator, and Array.map() to create the object you need.
const input = [
{ id: 1, fields: ["item", "2", "list"] },
{ id: 2, fields: ["sample", "1", "check"] }
];
const process = (input) => (Object.assign(...input.map(({ fields }) => (
fields.length ? { [fields[0]]: fields[0] } : {}
))));
console.log(process(input));
Your snippet was close, you just needed to clean up the variable names, and then using map makes it a bit neater too:
const obj = [
{id: 1, fields: ["item", "2", "list"]},
{id: 2, fields: ["sample", "1", "check"]}
]
function newObj(inputArray) {
let outputObject = {};
inputArray.map(item => item.fields[0])
.forEach(field => outputObject[field] = field);
return outputObject;
}
var result = newObj(obj)
console.log(result)

Cannot make JSON text out of javascript object

I'd like to convert this object that I receive from server to a JSON file so that I can use it in d3.js chart:
data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
The output should be:
{
"name" : "animal",
"children" : [
{"name":"dog", "value": 5},
{"name":"cat", "value": 4},
{"name":"fish", "value": 10}
]
}
What I came up with is:
var jsonText = [] ;
for ( key in data) {
jsonText.push({name : key.trim(), value : parseInt(data[key])});
}
But when I try to print out the object, I receive:
[object Object],[object Object],[object Object]
In addition to that I have no clue how to add other attributes to the JSON file. So appreciate your hints.
You can use Object.keys(data) and loop through the key to get the desired object structure.
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
var res = {
name: "animal",
children: []
};
Object.keys(data).forEach((key)=>{
res.children.push(
{name:key.trim(), value: parseInt(data[key])}
);
});
console.log(res);
You're almost there (the array is formatted correctly), but you need the resulting array to be the value of the children property of the object. It would also be a bit easier to use Object.entries and map, which tranforms an array into another array based on the same elements:
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
const children = Object.entries(data)
.map(([name, value]) => ({ name: name.trim(), value: Number(value) }));
const output = { name: 'animal', children };
console.log(output);
Assuming you're manually adding a key like animal this should work and the values should be ints.
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
var children = Object.keys(data).map((key) => {
return {
name: key.trim(),
value: parseInt(data[key])
}
})
let result = JSON.stringify({
name: 'animal',
children
})
console.log(result);
That will return
{"name":"animal","children":[{"name":"dog ","value":5},{"name":"cat ","value":4},{"name":"fish ","value":12}]}
Try - console.log(JSON.stringify(jsonText))
Create an object with children key and push value to it
let data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let newObj = {
"name": "animal",
"children": []
}
for (let keys in data) {
newObj.children.push({
name: keys.trim(),
value: parseInt(data[keys], 10)
});
}
console.log(newObj)
You could do something like this
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
Object.keys(data).reduce((obj, animal) => ({
...obj,
children: [
...obj.children,
{
name: animal,
value: data[animal]
}
]
}), {name: "animal", children: []})
console.log(JSON.stringify(obj))
This is a cleaner way to get the desired results in my opinion
You can just iterate over the data object using for..in and push prop: value pair objects into you children array:
const data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let obj = {
name: "animal",
children: []
}
for (prop in data) {
let animal = {}
animal[prop.trim()] = Number(data[prop])
obj.children.push(animal)
}
console.log(JSON.stringify(obj))

Combining JavaScript Arrays

I would like to take a JavaScript object that is formatted like:
results = {
names: [
"id",
"first_name"
],
values: [
[
1234,
"Fred"
],
[
4321,
"Joe"
],
[
1123,
"Mary"
]
]
}
and turn into this:
results = {
[id: 1234, name: "Fred"],
[id: 4321, name: "Joe"],
[id: 1123, name: "Mary"]
}
I tried doing something like this, but I can't get the structure correct:
var data = []
for (i=0; i < results['values'].length; i++ ){
var innerData = []
for (b=0; b < results['names'].length; b++ ){
innerData.push([name:results['names'][b], value: results['values'][i][b]])
}
data.push(innerData)
}
console.log(data)
Problem 1:
results = {
[id: 1234, name: "Fred"],
[id: 4321, name: "Joe"],
[id: 1123, name: "Mary"]
}
and
var data = []
and
[name:results['names'][b]…
An array [] consists a set of values in order.
An object {} consists of a set of key:value pairs.
You are using the wrong one each time. Use {} where you have [] and vice versa
Problem 2:
You say you want objects with id and name keys, but you are trying to create name and value keys. Use the property names you actually want.
Try this:
var data = [];
for (i in results['values']){
var innerData = {}
var value = results['values'][i];
for (b in value){
var key = results['names'][b];
innerData[key] = value[b];
}
data.push(innerData);
}
console.log(data);

Categories

Resources