如何绕过对象以获取特定数据?

huangapple go评论75阅读模式
英文:

How can I bypass the object to get the specific data?

问题

I see that you're trying to create a function to format the input data into a specific tree-like structure in JavaScript. Based on your code and the desired output, it looks like you want to format the data based on the "type" property in each object within the input data. Here's the corrected code:

const stylish = (data, replacer = ' ', spacesCount = 1) => {
  const iter = (data, depth) => {
    const arr = [];
    const keys = Object.keys(data);
    const sizeBefore = depth * spacesCount;
    const replacerBefore = replacer.repeat(sizeBefore);

    keys.forEach((key) => {
      if (data[key].type === 'object') {
        arr.push(`${replacerBefore}${key} : {\n${iter(data[key].value, depth + 1)}\n${replacerBefore}}`);
      } else if (data[key].type === 'added') {
        arr.push(`${replacerBefore}+ ${key} : ${iter(data[key].value, depth)}`);
      } else if (data[key].type === 'deleted') {
        arr.push(`${replacerBefore}- ${key} : ${iter(data[key].value, depth)}`);
      } else if (data[key].type === 'changed') {
        arr.push(`${replacerBefore}- ${key} : ${data[key].value1}`);
        arr.push(`${replacerBefore}+ ${key} : ${data[key].value2}`);
      } else if (data[key].type === 'nochanged') {
        arr.push(`${replacerBefore}${key} : ${data[key].value2}`);
      }
    });

    return arr.join('\n');
  };

  return `{\n${iter(data, 1)}\n}`;
};

You can call the stylish function with your input data to get the desired output:

const inputData = // Your input data here;
const formattedData = stylish(inputData);
console.log(formattedData);

This should produce the output you specified in your original request.

英文:

I have a object with values: { key: '', value: '', type: '' }. I need to realize formatter, which output tree from input data in output data. Please help me, because i can`t understand how i can do it, and please explain the answer. Please if you know any books or sites where i can understand objects, arrays, js. Thanks very much.

INPUT data:

         const el = [
{
"key": "common",
"value": [
{
"key": "follow",
"value": false,
"type": "added"
},
{
"key": "setting1",
"value1": "Value 1",
"value2": "Value 1",
"type": "nochanged"
},
{
"key": "setting2",
"value": 200,
"type": "deleted"
},
{
"key": "setting3",
"value1": true,
"value2": null,
"type": "changed"
},
{
"key": "setting4",
"value": "blah blah",
"type": "added"
},
{
"key": "setting5",
"value": {
"key5": "value5"
},
"type": "added"
},
{
"key": "setting6",
"value": [
{
"key": "doge",
"value": [
{
"key": "wow",
"value1": "",
"value2": "so much",
"type": "changed"
}
],
"type": "object"
},
{
"key": "key",
"value1": "value",
"value2": "value",
"type": "nochanged"
},
{
"key": "ops",
"value": "vops",
"type": "added"
}
],
"type": "object"
}
],
"type": "object"
},
{
"key": "group1",
"value": [
{
"key": "baz",
"value1": "bas",
"value2": "bars",
"type": "changed"
},
{
"key": "foo",
"value1": "bar",
"value2": "bar",
"type": "nochanged"
},
{
"key": "nest",
"value1": {
"key": "value"
},
"value2": "str",
"type": "changed"
}
],
"type": "object"
},
{
"key": "group2",
"value": {
"abc": 12345,
"deep": {
"id": 45
}
},
"type": "deleted"
},
{
"key": "group3",
"value": {
"deep": {
"id": {
"number": 45
}
},
"fee": 100500
},
"type": "added"
}
]

OUTPUT data:

            {
common: {
+ follow: false
setting1: Value 1
- setting2: 200
- setting3: true
+ setting3: null
+ setting4: blah blah
+ setting5: {
key5: value5
}
setting6: {
doge: {
- wow: 
+ wow: so much
}
key: value
+ ops: vops
}
}
group1: {
- baz: bas
+ baz: bars
foo: bar
- nest: {
key: value
}
+ nest: str
}
- group2: {
abc: 12345
deep: {
id: 45
}
}
+ group3: {
deep: {
id: {
number: 45
}
}
fee: 100500
}
}

I tried call function with recursive, but i don`t know what do next.

const stylish = (data, replacer = ' ', spacesCount = 1) => {
const iter = (data, depth) => {
const arr = [];
const keys = Object.keys(data);
const sizeBefore = depth * spacesCount;
const replacerBefore = replacer.repeat(sizeBefore);
keys.forEach((key) => {
if (data[key].type === 'object') {
arr.push(`${replacerBefore}  ${data[key].key} : ${iter(data[key].value)}`);
} if (data[key].type === 'added') {
arr.push(`${replacerBefore}+ ${data[key].key} : ${iter(data[key].value)}`);
} if (data[key].type === 'deleted') {
arr.push(`${replacerBefore}- ${data[key].key} : ${iter(data[key].value)}`);
} if (data[key].type === 'changed') {
arr.push(`${replacerBefore}- ${data[key].key} : ${data[key].value1}`);
arr.push(`${replacerBefore}+ ${data[key].key} : ${data[key].value2}`);
} if (data[key].type === 'nochanged') {
arr.push(`${replacerBefore}  ${data[key].key} : ${data[key].value2}`);
}
});
return [
'{',
...arr,
'}'
].join('\n');
};

What i get with my code:

Output:
{
common : {
+ follow : {
}
setting1 : Value 1
- setting2 : {
}
- setting3 : true
+ setting3 : null
+ setting4 : {
}
+ setting5 : {
}
setting6 : {
doge : {
- wow : 
+ wow : so much
}
key : value
+ ops : {
}
}
}
group1 : {
- baz : bas
+ baz : bars
foo : bar
- nest : [object Object]
+ nest : str
}
- group2 : {
}
+ group3 : {
}
}

答案1

得分: 0

处理复杂数据结构时,只需将不同类型的元素的处理分开,以便可以使用专用逻辑处理每种类型。

在您的情况下,有objects描述了对结构的更改。还有contents,它是这些更改的原始负载。

所以当遇到object时,嵌套项可以是objectcontent(字母是除了"type": "object"之外的每个条目)。使用相应的例程进一步处理它们。

当遇到content时,它要么是可以直接写入输出的原始值,要么是ArrayObject的实例,其项基本上是嵌套的contents

显然,为了保持正确的缩进,需要在处理的每一点跟踪当前嵌套级别。

英文:

When dealing with complex data structures, just separate processing of different types of elements so that you can handle each type with dedicated logic.

In your case you have objects which describe changes to the structure. And you have contents which is a raw payload of those changes.

So when you encounter object, nested items can be both object and content (the letter is every entry that is not "type": "object"). Process them further with corresponding routines.

And when you encounter content, it is either a primitive value that can be written to the output as is; or it is an instance of Array or Object whose items are basically nested contents.

Obviously, in order to maintain proper indenting, it is necessary to keep track of the current nesting level at every point of processing.


I did this demo for the sake of practice. It can detect errors in the structure and add them to the output (first call) or silently skip (second call).

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const input = [
{
&quot;key&quot;: &quot;common&quot;,
&quot;value&quot;: [
{
&quot;key&quot;: &quot;follow&quot;,
&quot;value&quot;: false,
&quot;type&quot;: &quot;added&quot;
},
{
&quot;key&quot;: &quot;setting1&quot;,
&quot;value1&quot;: &quot;Value 1&quot;,
&quot;value2&quot;: &quot;Value 1&quot;,
&quot;type&quot;: &quot;nochanged&quot;
},
{
&quot;key&quot;: &quot;setting2&quot;,
&quot;value&quot;: 200,
&quot;type&quot;: &quot;deleted&quot;
},
{
&quot;key&quot;: &quot;setting3&quot;,
&quot;value1&quot;: true,
&quot;value2&quot;: null,
&quot;type&quot;: &quot;changed&quot;
},
{
&quot;key&quot;: &quot;setting4&quot;,
&quot;value&quot;: &quot;blah blah&quot;,
&quot;type&quot;: &quot;added&quot;
},
{
&quot;key&quot;: &quot;setting5&quot;,
&quot;value&quot;: { &quot;key5&quot;: &quot;value5&quot; },
&quot;type&quot;: &quot;added&quot;
},
{
&quot;key&quot;: &quot;setting6&quot;,
&quot;value&quot;: [
{
&quot;key&quot;: &quot;doge&quot;,
&quot;value&quot;: [
{
&quot;key&quot;: &quot;wow&quot;,
&quot;value1&quot;: &quot;&quot;,
&quot;value2&quot;: &quot;so much&quot;,
&quot;type&quot;: &quot;changed&quot;
}
],
&quot;type&quot;: &quot;object&quot;
},
{
&quot;key&quot;: &quot;key&quot;,
&quot;value1&quot;: &quot;value&quot;,
&quot;value2&quot;: &quot;value&quot;,
&quot;type&quot;: &quot;nochanged&quot;
},
{
&quot;key&quot;: &quot;ops&quot;,
&quot;value&quot;: &quot;vops&quot;,
&quot;type&quot;: &quot;added&quot;
}
],
&quot;type&quot;: &quot;object&quot;
}
],
&quot;type&quot;: &quot;object&quot;
},
{
&quot;key&quot;: &quot;group1&quot;,
&quot;value&quot;: [
{
&quot;key&quot;: &quot;baz&quot;,
&quot;value1&quot;: &quot;bas&quot;,
&quot;value2&quot;: &quot;bars&quot;,
&quot;type&quot;: &quot;changed&quot;
},
{
&quot;key&quot;: &quot;foo&quot;,
&quot;value1&quot;: &quot;bar&quot;,
&quot;value2&quot;: &quot;bar&quot;,
&quot;type&quot;: &quot;nochanged&quot;
},
{
&quot;key&quot;: &quot;nest&quot;,
&quot;value1&quot;: { &quot;key&quot;: &quot;value&quot; },
&quot;value2&quot;: &quot;str&quot;,
&quot;type&quot;: &quot;changed&quot;
}
],
&quot;type&quot;: &quot;object&quot;
},
{
&quot;key&quot;: &quot;group2&quot;,
&quot;value&quot;: { &quot;abc&quot;: 12345, &quot;deep&quot;: { &quot;id&quot;: 45 } },
&quot;type&quot;: &quot;deleted&quot;
},
{
&quot;key&quot;: &quot;group3&quot;,
&quot;value&quot;: { &quot;deep&quot;: { &quot;id&quot;: { &quot;number&quot;: 45 } }, &quot;fee&quot;: 100500 },
&quot;type&quot;: &quot;added&quot;
},
{
&quot;key&quot;: &quot;RIDICULOUSLY-NESTED-ARRAY&quot;,
&quot;value1&quot;: [[[[[[&#39;BOOM!&#39;]]]]]],
&quot;value2&quot;: [[[[[[&#39;BOOM!&#39;]]]]]],
&quot;type&quot;: &quot;nochanged&quot;
},
{
&quot;key&quot;: &quot;CUSTOM-OBJECT&quot;,
&quot;value&quot;: {
&quot;EMPTY-OBJECT&quot;: {},
&quot;EMPTY-ARRAY&quot;: [],
&quot;ARRAY-OF-PRIMITIVES&quot;: [ 100, 200, 300 ],
&quot;ARRAY-OF-ARRAYS&quot;: [
[ &quot;Alice&quot;, &quot;Bob&quot; ],
[ &quot;Kent&quot;, &quot;Jessica&quot; ]
],
&quot;ARRAY-OF-OBJECTS&quot;: [
{ &quot;aaa&quot;: 111, &quot;bbb&quot;: 222, &quot;ccc&quot;: 333 },
{ &quot;ddd&quot;: 444, &quot;eee&quot;: 555, &quot;fff&quot;: 666 }
],
&quot;COMPLEX-ARRAY&quot;: [
&quot;next item is empty array&quot;, [],
&quot;next item is empty object&quot;, {},
{
&quot;ggg&quot;: { &quot;YES&quot;: &quot;NO&quot; },
&quot;hhh&quot;: [ true, false ],
&quot;iii&quot;: 10000000000000000111111110222203333n
},
null
]
},
&quot;type&quot;: &quot;added&quot;
},
&quot;INVALID ENTRY&quot;,
{
&quot;key&quot;: [&quot;INVALID KEY&quot;]
},
{
&quot;key&quot;: &quot;TEST-INVALID-TYPE&quot;,
&quot;type&quot;: &quot;INVALID TYPE&quot;
},
{
&quot;key&quot;: &quot;TEST-INVALID-OBJECT&quot;,
&quot;value&quot;: &quot;INVALID OBJECT&quot;,
&quot;type&quot;: &quot;object&quot;
},
{
&quot;key&quot;: &quot;TEST-EMPTY-OBJECT&quot;,
&quot;value&quot;: [],
&quot;type&quot;: &quot;object&quot;
}
];
function stylish (input, includeErrors) {
function writeNewline (string, level, sign) {
output += sign
? `\n${&#39;    &#39;.repeat(level - 1)}  ${sign} ${string}`
: `\n${&#39;    &#39;.repeat(level)}${string}`;
}
function writeError (message, level) {
if (level) {
writeNewline(`ERROR: ${message}`, level, &#39;!&#39;);
}
else {
output += `ERROR: ${message}`;
}
}
function writeNested (brackets, level, callback) {
output += brackets[0];
let savedLength = output.length;
callback();
if (savedLength == output.length) {
output += brackets[1];
}
else {
writeNewline(brackets[1], level);
}
}
function processContent (input, level) {
if (Array.isArray(input)) {
writeNested(&#39;[]&#39;, level, () =&gt; {
input.forEach((item) =&gt; {
writeNewline(&#39;&#39;, level + 1);
processContent(item, level + 1);
});
});
}
else if (typeof input == &#39;object&#39; &amp;&amp; input != null) {
writeNested(&#39;{}&#39;, level, () =&gt; {
Object.entries(input).forEach(([key, value]) =&gt; {
writeNewline(key + &#39;: &#39;, level + 1);
processContent(value, level + 1);
});
});
}
else {
output += input;
}
}
function processObjectEntry (input, level) {
if (typeof input == &#39;object&#39; &amp;&amp; input != null) {
let key = input.key;
if (typeof key != &#39;string&#39;) {
if (includeErrors) {
writeError(&#39;invalid &lt;key&gt; of entry&#39;, level);
}
return;
}
let prefix = key + &#39;: &#39;;
switch (input.type) {
case &#39;object&#39;:
if (Array.isArray(input.value)) {
writeNewline(prefix, level);
processObject(input.value, level);
}
else if (includeErrors) {
writeError(`entry &quot;${key}&quot; -&gt; &lt;value&gt; has to be an array`, level);
}
break;
case &#39;added&#39;:
writeNewline(prefix, level, &#39;+&#39;);
processContent(input.value, level);
break;
case &#39;deleted&#39;:
writeNewline(prefix, level, &#39;-&#39;);
processContent(input.value, level);
break;
case &#39;changed&#39;:
writeNewline(prefix, level, &#39;-&#39;);
processContent(input.value1, level);
writeNewline(prefix, level, &#39;+&#39;);
processContent(input.value2, level);
break;
case &#39;nochanged&#39;:
writeNewline(prefix, level);
processContent(input.value1, level);
break;
default:
if (includeErrors) {
writeError(`entry &quot;${key}&quot; -&gt; invalid &lt;type&gt;`, level);
}
}
}
else if (includeErrors) {
writeError(&#39;entry has to be an object&#39;, level);
}
}
function processObject (input, level) {
writeNested(&#39;{}&#39;, level, () =&gt; {
input.forEach((item) =&gt; processObjectEntry(item, level + 1));
});
}
let output = &#39;&#39;;
if (Array.isArray(input)) {
processObject(input, 0);
}
else if (includeErrors) {
writeError(&#39;input has to be an array&#39;);
}
return output;
}
console.log(stylish(input, true));
console.log(stylish(input));

<!-- language: lang-css -->

.as-console-wrapper { max-height: 100% !important; }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月26日 16:52:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定